声明没有var关键字的变量 [英] Declaring variables without var keyword

查看:31
本文介绍了声明没有var关键字的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 w3schools 有写:

At w3schools there is written:

如果你声明一个变量,而不使用var",这个变量总是会变成 GLOBAL.

If you declare a variable, without using "var", the variable always becomes GLOBAL.

在函数内部声明全局变量有用吗?我可以想象在某个事件处理程序中声明一些全局变量,但它有什么用呢?更好地使用 RAM?

Is it useful to declare global variable inside the function? I can imagine to declare some global variables in some event handler, but what is it good for? Better usage of RAM?

推荐答案

不,没有 RAM 好处或类似的东西.

No, there's no RAM benefit or anything like that.

w3schools 谈论的是我称之为 隐式全局变量的恐怖.考虑这个函数:

What w3schools is talking about is something I call The Horror of Implicit Globals. Consider this function:

function foo() {
    var variable1, variable2;

    variable1 = 5;
    varaible2 = 6;
    return variable1 + variable2;
}

看起来很简单,但它返回 NaN,而不是 11,因为 varaible2 = 6; 行上的拼写错误.它创建了一个带有拼写错误名称的全局变量:

Seems simple enough, but it returns NaN, not 11, because of the typo on the varaible2 = 6; line. And it creates a global variable with the typo'd name:

function foo() {
    var variable1, variable2;

    variable1 = 5;
    varaible2 = 6;
    return variable1 + variable2;
}
console.log(foo());     // NaN
console.log(varaible2); // 6?!?!?!

这是因为函数分配给了 varaible2(注意错字),但是 varaible2 没有在任何地方声明.通过 JavaScript 中作用域链的机制,这最终是对全局对象(您可以在浏览器上作为 window 访问)上的(新)属性的隐式赋值).

This is because the function assigns to varaible2 (note the typo), but varaible2 isn't declared anywhere. Through the mechanics of the scope chain in JavaScript, this ends up being an implicit assignment to a (new) property on the global object (which you can access as window on browsers).

那只是一个功能";在松散模式的 JavaScript 中,分配给完全未声明的标识符不是错误;相反,它在全局对象上创建一个属性,全局对象上的属性是全局变量.(在 ES5 之前,所有全局变量都是全局对象的属性.不过,从 ES2015 开始,添加了一种新的全局变量,它不是全局对象的属性.全局范围letconstclass 创建新的全局类型.)

That's just a "feature" of loose-mode JavaScript, assigning to a completely undeclared identifier isn't an error; instead, it creates a propertly on the global object, and properties on the global object are global variables. (Up through ES5, all globals were properties of the global object. As of ES2015, though, a new kind of global was added that isn't a property of the global object. Global-scope let, const, and class create the new kind of global.)

我的例子是一个错字,当然,如果你愿意,你可以故意这样做.毕竟,它是语言的一个明确定义的部分.所以:

My example is a typo, but of course, you could do it on purpose if you wanted. It's a clearly-defined part of the language, after all. So:

myNewGlobal = 42;

...任何没有声明 myNewGlobal 的地方都会创建新的全局.

...anywhere that myNewGlobal isn't declared will create the new global.

但我强烈建议永远不要故意这样做:它使代码难以阅读和维护,并且当 JavaScript 模块变得更加普遍和广泛时,这些代码将与 JavaScript 模块不兼容.如果您确实需要在运行时从函数内部创建全局变量(已经是一个危险信号,但有正当理由),请通过分配给 window 上的属性(或其他任何指的是您环境中的全局对象;它在浏览器上是 window):

But I would strongly recommend never doing it in purpose: It makes the code hard to read and maintain, and that code will be incompatible with JavaScript modules when they become more common and widespread. If you really need to create a global variable from within a function at runtime (already a red flag, but there are valid reasons for it), do it explicitly by assigning to a property on window (or whatever refers to the global object in your environment; it's window on browsers):

window.myNewGlobal = 42;

事实上,我建议使用 ES5 的 strict模式.严格模式使分配给未声明的标识符成为错误,而不是默默地创建全局.如果我们一直使用严格模式,上面的 foo 问题会更容易诊断:

In fact, I'd suggest using ES5's strict mode. Strict mode makes assigning to an undeclared identifier an error rather than silently creating a global. If we'd been using strict mode, the problem with foo above would have been much easier to diagnose:

"use strict"; // Turns on strict mode for this compilation unit

function foo() {
    var variable1, variable2;

    variable1 = 5;
    varaible2 = 6;                 // <=== ReferenceError
    return variable1 + variable2;
}
console.log(foo());

有点相切,但总的来说,我建议尽可能避免使用全局变量.全局命名空间在浏览器上已经非常非常混乱了.浏览器使用 id 为 DOM 中的每个元素创建一个全局变量,对于大多数具有 name 的元素,并且有几个自己预定义的全局变量(如 title) 很容易与您的代码发生冲突.

Somewhat tangential, but in general I'd recommend avoiding globals wherever possible. The global namespace is already very, very cluttered on browsers. The browser creates a global for every element in the DOM with an id, for most elements with a name, and has several predefined globals of its own (like title) which can easily conflict with your code.

相反,只需为自己定义一个很好的作用域函数并将您的符号放入其中:

Instead, just define yourself a nice scoping function and put your symbols in it:

(function() {
    var your, symbols, here, if_they_need, to_be_shared, amongst_functions;

    function doSomething() {
    }

    function doSomethingElse() {
    }
})();

如果你这样做,你可能想要启用严格模式:

And if you do that, you might want to enable strict mode:

(function() {
    "use strict";
    var your, symbols, here, if_they_need, to_be_shared, amongst_functions;

    function doSomething() {
    }

    function doSomethingElse() {
    }
})();

...,如前所述,它具有将未声明标识符的赋值转换为错误的优点(以及 各种其他有用的东西).

...which, as mentioned, has the advantage of turning assignments to undeclared identifiers into errors (along with various other helpful things).

请注意,在 JavaScript 模块(在 ES2015 中添加,但现在才开始流行)中,默认启用严格模式.(这也是 class 定义的情况,也是 ES2015 中的新定义.)

Note that in a JavaScript module (added in ES2015, but only now beginning to find their way into the wild), strict mode is enabled by default. (This is also the case with class definitions, also new in ES2015.)

这篇关于声明没有var关键字的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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