すべての変数が同じオブジェクトを指すようにしたい場合でも、その割り当てパターンには近づかないでください。
実際、最初の1つだけが変数宣言になり、残りは宣言されていない可能性のある識別子への割り当てにすぎません。
宣言されていない識別子(別名、宣言されていない割り当て)に値を割り当てることは、スコープチェーンで識別子が見つからない場合、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"