var是可选的吗?

myObj = 1;

和?

var myObj = 1;

我发现他们都工作从我的测试,我假设var是可选的。对吗?


当前回答

这不仅仅是局部和全局的区别。使用var创建的全局变量与不使用var创建的全局变量不同。考虑一下:

var foo = 1; // declared properly
bar = 2; // implied global
window.baz = 3; // global via window object

根据到目前为止的答案,这些全局变量foo、bar和baz都是等价的。事实并非如此。使用var创建的全局变量被(正确地)分配了内部[[DontDelete]]属性,这样它们就不能被删除。

delete foo; // false
delete bar; // true
delete baz; // true

foo; // 1
bar; // ReferenceError
baz; // ReferenceError

这就是为什么你应该总是使用var,即使是全局变量。

其他回答

不,它们不相等。

myObj = 1;您正在使用一个全局变量。

后一种声明在您使用的范围内创建一个局部变量。

尝试下面的代码来理解差异:

external = 5;
function firsttry() {
  var external = 6;
  alert("first Try: " + external);
}

function secondtry() {
  external = 7;
  alert("second Try: " + external);
}

alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7

第二个函数改变全局变量“external”的值,但第一个函数不会。

They mean different things. If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.

在我看来,这是javascript中最危险的问题之一,应该弃用,或者至少在警告中提出警告。原因是,很容易忘记var,并偶然地将一个通用变量名绑定到全局对象。这会产生奇怪且难以调试的行为。

Var是可选的。Var将变量置于局部作用域。如果一个变量在定义时没有使用var,那么它是在全局作用域中,是不可删除的。

edit

我认为不可删除的部分在特定的环境下在某个时间点是正确的。我一定是在做梦。

这不仅仅是局部和全局的区别。使用var创建的全局变量与不使用var创建的全局变量不同。考虑一下:

var foo = 1; // declared properly
bar = 2; // implied global
window.baz = 3; // global via window object

根据到目前为止的答案,这些全局变量foo、bar和baz都是等价的。事实并非如此。使用var创建的全局变量被(正确地)分配了内部[[DontDelete]]属性,这样它们就不能被删除。

delete foo; // false
delete bar; // true
delete baz; // true

foo; // 1
bar; // ReferenceError
baz; // ReferenceError

这就是为什么你应该总是使用var,即使是全局变量。

Var不允许程序员声明变量,因为Javascript没有变量。Javascript有对象。Var显式地向未定义的对象声明一个名称。赋值将一个名称作为句柄分配给已赋值的对象。

使用var告诉Javacript解释器两件事:

不使用委托反向遍历查找值的名称,而是使用此名称 不删除名字

省略var告诉Javacript解释器使用第一个找到的具有相同名称的对象的前一个实例。

Var作为关键字源于语言设计者的错误决定,就像Javascript作为名称源于错误决定一样。

ps.学习上面的代码示例。