var test = (function () {
var arr2 = [1, 2, 3, 3];
return function () { return arr2; };
})();
Array.prototype.f1 = function () { return []; };
Array.prototype.f2 = function () { this.length = 0; return this; };
var arr = test(); console.log(arr.length); // 4 arr.f1(); arr = test(); console.log(arr.length); // 仍然是 4
f1 只是 return [],並沒有對 this 做任何事,所以原本陣列安然無恙。
var arr = test(); console.log(arr.length); // 4 arr.f2(); arr = test(); console.log(arr.length); // 0
test() 每次回傳的不是複本,而是同一個 arr2 的參照。閉包讓 arr2 持續存活,但也意味著它是被共用的單一實例。
接著看 f2:
Array.prototype.f2 = function () { this.length = 0; return this; };
用 arr.f2() 呼叫時,this 就是 arr,而 arr 正是 arr2 本身。所以 this.length = 0 直接把閉包裡的 arr2 清空了。下一次呼叫 test() 拿到的自然是長度 0。
對照之下 f1 沒有碰 this,所以看起來「沒事」——但這只是巧合,並非閉包保護了它。
return arr2.slice()。for...in 出現意料之外的鍵。要擴充請用獨立函式或自訂類別。this.length = 0 這類破壞性操作要格外小心,因為 this 指向的就是呼叫者本身,改動會直接反映到所有持有該參照的地方。