請離開從該分配模式,即使您想讓所有變量指向同一個對象。
事實上,只有第一個將是一個變量聲明,其餘都只是分配到可能未申報的標識符!
強烈建議將值指定給未聲明的標識符(又名未聲明的賦值),因爲如果在範圍鏈中找不到標識符,則會創建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第5嚴格模式不允許這種分配。 在嚴格模式下,對未聲明的標識符進行分配將導致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"
來源
2010-11-02 22:29:14
CMS
Bonuspoint不使用'' – DanMan 2010-11-02 22:18:18
我有問題,新的Array(),符合市場預期。感謝您的解釋! – FFish 2010-11-02 22:24:18
演示如何工作的獎勵;) – jcolebrand 2010-11-02 22:24:18