DIV CSS 佈局教程網

JavaScript 的 prototype 與 constructor:一次搞懂原型鏈的兩個關鍵角色
編輯:JavaScript綜合知識     

這兩個屬性是 JavaScript 原型機制的入門難關。搞懂了,繼承與原型鏈就不再是黑箱。

一、constructor:指向建立這個物件的函式

constructor 的值是一個函式。在 JavaScript 中,除了 null 與 undefined,其他型別的值、陣列、函式與物件都具有這個屬性,其值就是該值的建構函式。

var a = 12,                                  // 數字
    b = 'str',                               // 字串
    c = false,                               // 布林
    d = [1, 'd', function () { return 5; }],  // 陣列
    e = { name: 'e' },                       // 物件
    f = function () { return 'function'; };  // 函式

console.log('a: ', a.constructor);   // Number()
console.log('b: ', b.constructor);   // String()
console.log('c: ', c.constructor);   // Boolean()
console.log('d: ', d.constructor);   // Array()
console.log('e: ', e.constructor);   // Object()
console.log('f: ', f.constructor);   // Function()

這些都是內建的建構函式,我們也能自訂:

function A(name) {
    this.name = name;
}

var a = new A('a');
console.log(a.constructor);   // A(name)

呼叫建構函式時必須用 new 關鍵字,因為它回傳的是一個物件:

var a = 4;
var b = new Number(4);

console.log('a: ', typeof a);   // number
console.log('b: ', typeof b);   // object

這也解釋了為什麼 new Number(5) 的 typeof 是 'object'——装箱後它就是個物件了。

二、prototype:函式的原型物件

prototype 是函式才有的屬性。預設情況下,一個函式的 prototype 是一個與函式同名的空物件;匿名函式的 prototype 名稱為 Object。

function fn() {}
console.log(fn.prototype);   // fn { }

它主要用來實作繼承。所有透過 new fn() 建立的實例,都會隱式繼承 fn.prototype 上的屬性與方法:

function A(name) { this.name = name; }
A.prototype.show = function () { console.log(this.name); };

function B(name) { this.name = name; }
B.prototype = A.prototype;

var test = new B('test');
test.show();   // test

三、一個必須修正的細節

上面的寫法有問題:test 的 constructor 其實是 A,而不是 B。

console.log(test.constructor);   // A(name)

原因就在 B.prototype = A.prototype 這一行:它把 B 的 prototype 直接指向 A 的 prototype 物件,而該物件上的 constructor 仍舊指向 A。修正方式是把 constructor 還原回來:

function A(name) { this.name = name; }
A.prototype.show = function () { console.log(this.name); };

function B(name) { this.name = name; }
B.prototype = A.prototype;
B.prototype.constructor = B;      // 關鍵修正

var test = new B('test');
test.show();                      // test
console.log(test.constructor);    // B(name)

為什麼要這樣做?因為 prototype 的值是一個物件,而這個物件的 constructor 屬性指回它所在的函式:

console.log(A.prototype.constructor === A);   // true

四、更完整的繼承寫法

直接共用同一個 prototype 物件,意味著 A 和 B 完全被綁死——日後替 B 加方法,A 也會跟著長出同一個方法。實務上應該建立一層原型鏈,而不是共用同一個物件:

function A(name) { this.name = name; }
A.prototype.show = function () { console.log(this.name); };

function B(name) { A.call(this, name); }   // 借用父建構函式初始化屬性

B.prototype = Object.create(A.prototype);  // 建立原型鏈,而非共用
B.prototype.constructor = B;               // 還原 constructor

var test = new B('test');
test.show();                                // test
console.log(test.constructor === B);        // true
console.log(test instanceof A);             // true

而 ES6 的 class 語法糖把這一切都封裝好了,底層仍然是原型:

class A {
    constructor(name) { this.name = name; }
    show() { console.log(this.name); }
}

class B extends A {
    constructor(name) { super(name); }
}

var test = new B('test');
test.show();
console.log(test.constructor === B);   // true,自動處理好了

理解 prototype 與 constructor 的價值,在於當你遇到「為什麼改了父類別的方法,子類別也跟著變」或「為什麼 constructor 對不上」這類問題時,能直接從原型鏈的角度找到答案,而不是靠試錯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved