this、constructor、prototype 是 JavaScript 面試和閱讀源碼時反覆出現的三個概念。它們的規則並不難,難的是零散地知道、卻沒有串起來。本文把三者放在一起梳理,試著建立一條完整的推導鏈。
this 指代當前對象。在全局作用域中使用時,它指向全局對象 window;在函數中使用時,它指向調用該函數的對象——注意是調用時決定,而非定義時。
console.log(this === window); // true
console.log(window.alert === this.alert); // true
console.log(this.parseInt('021', 10)); // 10
看一個更能說明問題的例子:
function foo() {
console.log(this.fruit);
}
var fruit = 'apple'; // 等價於 window.fruit = 'apple'
foo(); // 'apple',此時 this 指向 window
// 這種寫法與 window.foo() 完全等價
var pack = { fruit: 'orange', foo: foo };
pack.foo(); // 'orange',同一個函數,this 變成了 pack
同一個 foo,調用方式不同,this 就不同。這就是「運行時決定」的含義。
用 apply/call 顯式改變指向。
function foo() { console.log(this.fruit); }
var fruit = 'apple';
var pack = { fruit: 'orange' };
foo.apply(window); // 'apple'
foo.apply(pack); // 'orange'
apply 和 call 作用完全相同,唯一差別是參數形式:call 逐个列出,apply 第二個參數數組傳遞。
函數也是對象,所以函數可以有屬性。
function foo() {
if (this === window) console.log('this is window.');
}
foo.boo = function () {
if (this === foo) console.log('this is foo.');
else if (this === window) console.log('this is window.');
};
foo(); // this is window.
foo.boo(); // this is foo.
foo.boo.apply(window); // this is window.
把這幾段代碼放在一起看,就能總結出 this 的判定優先級:new 綁定 > 顯式綁定(call/apply/bind)> 隱式綁定(對象方法調用)> 默認綁定(全局)。ES6 的箭頭函數是個例外,它沒有自己的 this,會捕獲定義所在作用域的 this,且無法被 call/apply 改變。
prototype 本質上就是一個普通 JavaScript 對象。每個函數都有一個默認的 prototype 屬性;當這個函數被用作構造函數時,new 出來的所有實例都會把這個 prototype 對象作為自己的原型,從而能共享上面定義的方法。
function Person(name) {
this.name = name; // 實例屬性,每個對象一份
}
Person.prototype = {
getName: function () { // 原型方法,所有實例共享
return this.name;
}
};
var hao = new Person('haorooms');
console.log(hao.getName()); // haorooms
反過來看內建類型也是同理。字符串、數字、數組、對象、日期,內部都是用構造函數實現的:
function Array() { /* 預定義類型 */ }
var arr1 = new Array(1, 56, 34, 12);
var arr2 = [1, 56, 34, 12]; // 但我們更習慣字面量語法
數組的 concat、join、push 等方法就定義在 Array.prototype 上。所有內建類型都具有只讀的 prototype 屬性——這很合理,否則改動一下內建方法就全沒了——但我們可以向其中擴展自己的方法:
Array.prototype.min = function () {
var min = this[0];
for (var i = 1; i < this.length; i++) {
if (this[i] < min) min = this[i];
}
return min;
};
console.log([1, 56, 34, 12].min()); // 1
這裡有個經典陷阱。向數組原型加了可枚舉屬性後,for...in 遍歷數組時會把它也遍歷出來:
var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
total += parseInt(arr[i], 10);
}
console.log(total); // NaN,因為 min 函數被加進來了
解法是用 hasOwnProperty 過濾掉原型鏈上的屬性:
var total = 0;
for (var i in arr) {
if (arr.hasOwnProperty(i)) {
total += parseInt(arr[i], 10);
}
}
console.log(total); // 103
這也是為什麼給內建原型擴展方法被普遍認為是危險做法:你可能不知道項目裡哪個第三方庫正在用 for...in 遍歷數組。ES6 之後的正確做法是直接聲明為不可枚舉屬性。
var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array); // true,等價於 new Array(1,56,34,12)
var Foo = function () {};
console.log(Foo.constructor === Function); // true,等價於 new Function()
var obj = new Foo();
console.log(obj.constructor === Foo); // true
console.log(obj.constructor.constructor === Function); // true
當 constructor 遇到 prototype,事情開始有趣。函數默認的 prototype 對象上有一個 constructor 屬性指回這個函數本身:
function Person(name) { this.name = name; }
Person.prototype.getName = function () { return this.name; };
var p = new Person('haorooms');
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true
注意上面用的是修改 Person.prototype.getName,而不是覆蓋整個 prototype。如果是後者,行為就變了:
function Person(name) { this.name = name; }
Person.prototype = {
getName: function () { return this.name; }
};
var p = new Person('haorooms');
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
原因很簡單:覆蓋 prototype 等價於執行 Person.prototype = new Object({...}),而 constructor 始終指向創建自身的構造函數,此時自然變成了 Object:
console.log(p.constructor === Object); // true
修正方法就是把 constructor 補回去:
Person.prototype.constructor = Person;
// 或者在字面量裡直接聲明
Person.prototype = {
constructor: Person,
getName: function () { return this.name; }
};
三者的關係可以濃縮成一句話:prototype 是函數上的一個對象,new 會讓新實例的原型指向它,而 constructor 是這個原型對象上的一個指針,回指那個函數。理解了這條鏈,就能明白為什麼 ES6 的 class 需要寫 constructor、為什麼 extends 要同時處理原型鏈和 constructor 鏈(也就是所謂的 __proto__ 雙向關聯)、以及為什麼很多工具庫都要在繼承後手動修 constructor。
實務建議只有兩條:能用 class 語法就用,讓引擎和語法糖替你處理這些細節;必須手寫原型鏈時,記得覆蓋 prototype 之後補上 constructor。