什么是"var"?用JavaScript做吗?为什么有时将其作为作业的一部分? [英] What does "var" do in JavaScript? Why is it sometimes part of an assignment?

查看:38
本文介绍了什么是"var"?用JavaScript做吗?为什么有时将其作为作业的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在JavaScript中使用var和不使用var之间的区别

  var foo = 1;foo = 1; 

以上两行有什么区别?

解决方案

基本上, var 声明变量,您也可以同时分配给它./p>

没有 var ,它将分配给变量.分配将分配给现有变量或创建具有该名称的全局变量,然后分配给它.

在函数之外,这意味着如果变量不存在,则在原理上没有任何实际差异.在这种情况下,两者都会创建全局变量 foo .

函数中,有很大的不同.第一个创建函数局部变量,无论该变量是否存在于其他地方.

如果不存在第二个变量,它将创建一个全局变量,或者如果存在则简单地更改值.

为了使代码尽可能模块化,除非您特别想更改现有的全局变量,否则应始终使用 var .这意味着使用 var 声明函数之外的所有全局变量,并使用 var 声明所有局部变量.

Possible Duplicate:
Difference between using var and not using var in JavaScript

var foo = 1;

foo = 1;

What is the difference between above two lines ?

解决方案

Basically, var declares a variable and you can also assign to it at the same time.

Without var, it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it.

Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable foo in that case.

Within a function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere.

The second will create a global variable if it doesn't exist, or simply change the value if it does exist.

In order to keep code as modular as possible, you should always use var unless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with var and declaring all locals with var.

这篇关于什么是"var"?用JavaScript做吗?为什么有时将其作为作业的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆