面試時被問到過這麼一段程式碼,當時覺得自己答得挺篤定,事後才發現差點掉進另一道相似題目的陷阱裡。
var Fundamental = {count: 1};
function Test() {}
Test.prototype = Fundamental;
Test.prototype.increase = function () { this.count++; };
var test = new Test();
console.log(test.count);
var test2 = new Test();
console.log(test2.count);
test.increase();
// test.count 和 test2.count 各是多少?
很多人一看到這題,腦中浮現的其實是另一個寫法——把屬性放進閉包裡:
function FundamentalModified() {
var count = 1;
this.increase = function () { count++; };
this.show = function () { return count; };
}
function TestModified() {}
TestModified.prototype = new FundamentalModified();
var test3 = new TestModified();
var test4 = new TestModified();
test3.increase();
// test3.show() 和 test4.show() 各是多少?
這一版單純得多:count 被閉包各自捕獲,兩個實例互不干擾,答案顯而易見。但兩題的結果並不一樣,把它們混為一談就會答錯。
關鍵在於分清所有權。呼叫 test.increase() 之前,test 自身並沒有 count 屬性,它拿到的 count 來自原型鏈;而 test2 的 count 同樣是 test2.__proto__ 上的屬性。
執行 this.count++ 時,看似一句話,實際上做了兩件事:先讀出 this.count,再把它加一後寫回去。
this.count = this.count + 1;
而「寫回去」這個動作,語義並不是修改原型上的屬性,而是在實例自身建立一個同名屬性,值取 this.count + 1。所以第一次執行時,等價於:
this.count = Test.prototype.count + 1; // 1 + 1 = 2
用 hasOwnProperty 驗證就很直觀:
var test = new Test();
test.hasOwnProperty("count"); // false,count 還在原型上
test.increase();
test.hasOwnProperty("count"); // true,實例上有了自己的 count(值為 2)
於是 test.count 是 2,而 test2.count 依舊沿著原型鏈讀到那個從未被改動的 1。
這類題目的價值不在於答案本身,而在於它逼你說清楚「讀屬性走原型鏈,寫屬性落在實例上」這條規則。面試官真正想聽的,是你有沒有把原型鏈這件事想透。