DIV CSS 佈局教程網

JavaScript 中 prototype 與 constructor 一次搞懂
編輯:JavaScript基礎知識     

初次接觸 JavaScript 原型機制時,prototype 與 constructor 這兩個概念往往最容易讓人暈頭轉向。本文用清晰的例子把兩者的關係梳理明白。

一、constructor:指向構造函數的指針

constructor 的值始終是一個函數。在 JavaScript 裡,除了 null 和 undefined 之外,數字、字串、布林值、陣列、函數與物件都帶有一個 constructor 屬性,它指向產生這個值的構造函數。

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

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

這些都是 JavaScript 內建的構造函數,當然我們也能自訂:

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(typeof a); // number
console.log(typeof b); // object

二、prototype:函數的共有財產

prototype 是函數特有的屬性。預設情況下,它的值是一個與函數同名的空物件,而匿名函數的 prototype 則名為 Object:

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

原型屬性最主要的用途,就是實作 JavaScript 的繼承機制:

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 的構造函數其實變成了 A 而非 B:

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

原因就在於 B.prototype = A.prototype 這句把 B 的原型構造函數一併改成了 A。要修正它,只需把構造函數指回來:

B.prototype = A.prototype;
B.prototype.constructor = B;

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

之所以需要這麼做,是因為原型本身也是一個物件,而它的構造函數正是建立它的那個函數,兩者互為呼應:

console.log(A.prototype.constructor === A); // true
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved