即使您想让所有变量都指向同一个对象,也请远离该分配模式。
事实上,只有第一个是变量声明,其余的只是对可能未声明的标识符的赋值!
强烈建议不要为未声明的标识符(也称为未声明的赋值)赋值,因为如果在作用域链上找不到标识符,则会创建一个 GLOBAL 变量。例如:
function test() {
// We intend these to be local variables of 'test'.
var foo = bar = baz = xxx = 5;
typeof foo; // "number", while inside 'test'.
}
test();
// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined", As desired, but,
typeof bar; // "number", BAD!, leaked to the global scope.
typeof baz; // "number"
typeof xxx; // "number"
此外,ECMAScript 5th Strict Mode 不允许这种分配。在严格模式下,对未声明标识符的赋值将导致TypeError
异常,以防止隐含的全局变量。
相比之下,如果写得正确,这是我们看到的:
function test() {
// We correctly declare these to be local variables inside 'test'.
var foo, bar, baz, xxx;
foo = bar = baz = xxx = 5;
}
test();
// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined"
typeof bar; // "undefined"
typeof baz; // "undefined"
typeof xxx; // "undefined"