在 JavaScript 中,每個物件都有一個內建的 prototype 屬性。它保存著對另一個 JavaScript 物件的參照,而這個物件就充當著當前物件的「父物件」。
A.prototype = new B();
理解 prototype 時,不應把它和繼承混為一談。A 的 prototype 是 B 的一個實例,可以想成 A 把 B 的方法與屬性全部複製了一份,因此 A 能使用 B 的方法與屬性——這裡強調的是「複製」而非「繼承」。甚至可以出現這樣的情況:A 的 prototype 是 B 的實例,同時 B 的 prototype 又是 A 的實例。
在函式內部定義的變數與函式,若不對外提供介面,外部就無法存取,這就是該函式的私有成員。
<script type="text/javascript">
function Box(){
var color = "blue"; // 私有變數
var fn = function() // 私有函式
{
}
}
</script>
因此在 Box 外部無法存取 color 與 fn:
var obj = new Box(); alert(obj.color); // 彈出 undefined alert(obj.fn); // 同上
定義函式後,透過點號「.」為它添加的屬性與函式,函式本身可以存取,但其实例卻存取不到,這類成員稱為靜態變數與靜態函式。
<script type="text/javascript">
function Obj(){};
Obj.num = 72; // 靜態變數
Obj.fn = function() // 靜態函式
{
}
alert(Obj.num); // 72
alert(typeof Obj.fn); // function
var t = new Obj();
alert(t.name); // undefined
alert(typeof t.fn); // undefined
</script>
除了靜態成員,我們通常也希望在物件定義時就一併定義一些實例化後才能存取的屬性與方法,JavaScript 同樣做得到:
<script type="text/javascript">
function Box(){
this.a = []; // 實例變數
this.fn = function(){ // 實例方法
}
}
console.log(typeof Box.a); // undefined
console.log(typeof Box.fn); // undefined
var box = new Box();
console.log(typeof box.a); // object
console.log(typeof box.fn); // function
</script>
而為實例變數與方法動態添加新成員時,各實例之間互不相干:
<script type="text/javascript">
function Box(){
this.a = []; // 實例變數
this.fn = function(){ // 實例方法
}
}
var box1 = new Box();
box1.a.push(1);
box1.fn = {};
console.log(box1.a); // [1]
console.log(typeof box1.fn); // object
var box2 = new Box();
console.log(box2.a); // []
console.log(typeof box2.fn); // function
</script>
在 box1 中修改了 a 與 fn,box2 卻不受影響。由於陣列與函式都是引用型別的物件,這說明 box1 與 box2 中雖有同名成員,卻各自指向不同的參照,是對 Box 定義的一次複製。
對屬性來說這沒什麼問題,但對方法來說卻很棘手:每個方法做的功能完全相同,卻被複製了兩份。若一個函式物件有成千上萬個實例方法,每個實例都要保有一份複製,顯然不合理。於是 prototype 應運而生。
我們建立的每個函式都有一個 prototype 屬性,它是一個指向物件的指標,而該物件的用途是存放能由特定型別的所有實例共享的屬性與方法。也就是說,prototype 就是透過呼叫構造函式所建立之物件的原型物件。
使用原型的好處在於,能讓物件實例共享其中的屬性與方法,不必在構造函式中重複定義。在 JavaScript 中有兩種型別的值:原始值與物件值。每個物件都有一個內部屬性 prototype(原型),它的值可以是一個物件,也可以是 null;若是一個物件,則該物件同樣有自己的原型,這樣便形成一條線性的鏈,我們稱之為原型鏈。
函式可以用來作為構造函式使用。只有函式才有 prototype 屬性並可存取,而物件實例並不具備該屬性,只有一個內部且不可存取的 __proto__ 屬性。__proto__ 是物件中指向相關原型的神祕連結;依標準它並不對外公開,但 Firefox 引擎將它暴露了出來,讓我們得以存取與設定。
<script type="text/javascript">
var Browser = function(){};
Browser.prototype.run = function(){
alert("I'm Gecko, a kernel of firefox");
}
var Bro = new Browser();
Bro.run();
</script>
當呼叫 Bro.run() 時,由於 Bro 本身沒有這個方法,於是便往它的 __proto__(也就是 Browser.prototype)去找,最終執行了 run()。(此處函式名首字母大寫者代表構造函式,用以區別普通函式。)
當以構造函式建立實例時,實例內部會包含一個內部指標(__proto__)指向構造函式的 prototype,這個連結存在於「實例與構造函式的 prototype」之間,而非實例與構造函式之間。
<script type="text/javascript">
function Person(name){ // 構造函式
this.name = name;
}
Person.prototype.printName = function() // 原型物件
{
alert(this.name);
}
var person1 = new Person('Byron'); // 實例化物件
console.log(person1.__proto__); // Person
console.log(person1.constructor); // 可以試試會得到什麼
console.log(Person.prototype); // 指向原型物件 Person
var person2 = new Person('Frank');
</script>
Person 的實例 person1 包含 name 屬性,同時自動產生一個 __proto__ 屬性指向 Person 的 prototype,藉此可存取原型內定義的 printName 方法,概念如下圖:

每個 JavaScript 函式都有 prototype 屬性,它參照一個物件,也就是原型物件。原型物件初始化時是空的,我們可以在裡面自訂任意屬性與方法,這些成員都將被該構造函式所建立的物件繼承。
實例透過構造函式建立,一經創造便具備 constructor 屬性(指向構造函式)與 __proto__ 屬性(指向原型物件);構造函式有一個 prototype 屬性,指向它的原型物件;原型物件內部也有一个指標(constructor 屬性)指回構造函式:Person.prototype.constructor = Person; 而實例可以存取原型物件上定義的屬性與方法。
再舉個例子:
<script type="text/javascript">
function Animal(name) // 基礎構造函式
{
this.name = name; // 設定物件屬性
}
Animal.prototype.behavior = function() // 為 prototype 添加 behavior 方法
{
alert("this is a " + this.name);
}
var Dog = new Animal("dog"); // 建立 Dog 物件
var Cat = new Animal("cat"); // 建立 Cat 物件
Dog.behavior(); // 透過物件直接呼叫 behavior 方法
Cat.behavior(); // 輸出 "this is a cat"
alert(Dog.behavior == Cat.behavior); // 輸出 true
</script>
從執行結果可以看出,構造函式 prototype 上定義的方法確實能透過物件直接呼叫,而且程式碼是共享的。在這裡,prototype 屬性指向 Animal 物件。
當我們建立 array1 這個物件時,它在 JavaScript 引擎中的物件模型如下:
var array1 = [1, 2, 3];

array1 有一個 length 屬性值為 3,我們可以透過下面的方式為它增加元素:
array1.push(4);
push 這個方法來自 array1 的 __proto__ 所指向物件上的方法(Array.prototype.push())。正因所有以 [] 建立的陣列物件都含有一個指向同一個具備 push、reverse 等方法的物件(Array.prototype)的 __proto__,這些陣列才能使用 push、reverse 等方法。
function Base() {
this.id = "base"
}

var obj = new Base();
我們在 JavaScript 引擎中看到的物件模型如下:

那麼 new 運算子究竟做了什麼?其實很簡單,就三件事:
var obj = {};
obj.__proto__ = Base.prototype;
Base.call(obj);
當從一個物件取值或方法時,若該物件本身不存在這樣的成員,就會去它關聯的 prototype 物件尋找;若 prototype 沒有,就再去 prototype 所關聯的前一層 prototype 尋找,以此類推,直到 prototype 為 undefined(Object 的 prototype 就是 undefined),从而形成所謂的「原型鏈」。
<script type="text/javascript">
function Shape(){
this.name = "shape";
this.toString = function(){
return this.name;
}
}
function TwoShape(){
this.name = "2 shape";
}
function Triangle(side, height){
this.name = "Triangle";
this.side = side;
this.height = height;
this.getArea = function(){
return this.side * this.height / 2;
}
}
TwoShape.prototype = new Shape();
Triangle.prototype = new TwoShape();
</script>
這裡用構造函式 Shape() 建立一個實體,再用它覆蓋該物件的原型。為避免 constructor 指標錯亂,通常會補回正確的 constructor:
<script type="text/javascript">
function Shape(){
this.name = "shape";
this.toString = function(){
return this.name;
}
}
function TwoShape(){
this.name = "2 shape";
}
function Triangle(side, height){
this.name = "Triangle";
this.side = side;
this.height = height;
this.getArea = function(){
return this.side * this.height / 2;
}
}
TwoShape.prototype = new Shape();
Triangle.prototype = new TwoShape();
TwoShape.prototype.constructor = TwoShape;
Triangle.prototype.constructor = Triangle;
var my = new Triangle(5, 10);
my.getArea();
my.toString(); // Triangle
my.constructor; // Triangle(side, height)
</script>
在原型鏈的末端,就是 Object 構造函式 prototype 所指向的那個原型物件。它是所有物件的祖先,實現了 toString 等所有物件天生該具備的方法。其他內建構造函式(如 Function、Boolean、String、Date、RegExp 等)的 prototype 都從這個「老祖宗」傳承而來,同時各自定義了自身的屬性與方法,因此它們的後代才表現出各自的特徵。
在 ECMAScript 中,實作繼承靠的就是原型鏈:
<script type="text/javascript">
function Box(){ // 被繼承的函式叫做超型別(父類、基類)
this.name = "Jack";
}
function Tree(){ // 繼承的函式叫做子型別(子類、派生類)
this.age = 300;
}
// 透過原型鏈繼承,赋值給子型別的 prototype
Tree.prototype = new Box(); // Tree 繼承了 Box,透過原型形成鏈條
var tree = new Tree();
alert(tree.name); // 彈出 Jack
</script>
原型鏈雖然強大,卻也存在問題。最主要的問題來自「包含引用型別值的原型」:這類原型屬性會被所有實例共享,這也正是為什麼要在構造函式中(而非原型物件中)定義屬性的原因。透過原型實作繼承時,原型實際上會變成另一個型別的實例,於是原本的實例屬性也變成了原型的屬性。此外,建立子型別實例時,無法在不影響所有物件實例的前提下,向超型別的構造函式傳遞參數。正因這些限制,實務上很少單獨使用原型鏈。
再看一個例子:
<script type="text/javascript">
function Person(name)
{
this.name = name; // 設定物件屬性
};
Person.prototype.company = "Microsoft"; // 設定原型的屬性
Person.prototype.SayHello = function() // 原型的方法
{
alert("Hello, I'm " + this.name + " of " + this.company);
};
var BillGates = new Person("BillGates"); // 建立 person 物件
BillGates.SayHello(); // 繼承原型內容,輸出 "Hello, I'm BillGates of Microsoft"
var Jobs = new Person("Jobs");
Jobs.company = "Apple"; // 設定自己的 company,覆蓋了原型的 company
Jobs.SayHello = function()
{
alert("Hi, " + this.name + " like " + this.company);
};
Jobs.SayHello(); // 自己覆蓋的屬性與方法,輸出 "Hi, Jobs like Apple"
BillGates.SayHello(); // Jobs 的覆蓋不影響原型,BillGates 依舊照常輸出
</script>
再看一個較完整的原型鏈例子:
<script type="text/javascript">
function Year(){
this.value = 21;
}
Year.prototype = {
method: function(){
}
};
function Hi(){
};
// 設定 Hi 的 prototype 屬性為 Year 的實例物件
Hi.prototype = new Year();
Hi.prototype.year = 'Hello World';
Hi.prototype.constructor = Hi;
var test = new Hi(); // 建立一個 Hi 的新實例
// 原型鏈
test [Hi 的實例]
Hi.prototype [Year 的實例]
{year: 'Hello World'}
Year.prototype
{method: ……};
object.prototype
{toString: ...};
</script>
從上例可知,test 物件從 Hi.prototype 與 Year.prototype 繼承下來,因此它能存取 Year 的原型方法 method,同時也能存取實例屬性 value。
__proto__ 屬性(IE 不支援)是實例指向原型物件的一個指標,其作用是指向構造函式的原型屬性,透過它就能存取原型裡的屬性與方法。JavaScript 的物件實例本質上由一系列屬性組成,其中有一個內部不可見的特殊屬性——__proto__,它的值指向該實例的原型,而一個實例只擁有一個唯一的原型。
<script type="text/javascript">
function Box(){ // 大寫,代表構造函式
Box.prototype.name = "trigkit4"; // 原型屬性
Box.prototype.age = "21";
Box.prototype.run = function() // 原型方法
{
return this.name + this.age + ' studying';
}
}
var box1 = new Box();
var box2 = new Box();
alert(box1.constructor); // 構造屬性,可取得構造函式本身,
// 作用是被原型指標定位後取得構造函式本身
</script>
<script type="text/javascript">
function Box(){ // 大寫,代表構造函式
Box.prototype.name = "trigkit4"; // 原型屬性
Box.prototype.age = "21";
Box.prototype.run = function() // 原型方法
{
return this.name + this.age + ' studying';
}
}
var box1 = new Box();
alert(box1.name); // trigkit4,原型裡的值
box1.name = "Lee";
alert(box1.name); // Lee,就近原則
var box2 = new Box();
alert(box2.name); // trigkit4,原型的值,沒有被 box1 修改
</script>
<script type="text/javascript">
function Box(){
this.name = "Bill";
}
Box.prototype.name = "trigkit4"; // 原型屬性
Box.prototype.age = "21";
Box.prototype.run = function() // 原型方法
{
return this.name + this.age + ' studying';
}
var box1 = new Box();
alert(box1.name); // Bill,實例裡的值優先
box1.name = "Lee";
alert(box1.name); // Lee,就近原則
</script>
<script type="text/javascript">
function Person(){};
Person.prototype.name = "trigkit4";
Person.prototype.say = function(){
alert("Hi");
}
var p1 = new Person(); // prototype 是 p1 與 p2 的原型物件
var p2 = new Person(); // 實例內部有一個 __proto__,指向 Person 的 prototype
console.log(p1.prototype); // undefined,該屬性是一個物件,存取不到
console.log(Person.prototype); // Person
console.log(Person.prototype.constructor); // 原型物件內部也有 constructor 指向構造函式
console.log(p1.__proto__); // 指向 prototype 原型物件的指標
p1.say(); // 實例可存取原型物件上定義的屬性與方法
</script>
function createObject(name, age){
var obj = new Object();
obj.name = name;
obj.age = age;
return obj;
}
工廠模式解決了實例化物件大量重複的問題,但仍有一個缺陷:根本無法辨明它們究竟是哪個物件的實例。而使用構造函式,既解決了重複實例化的問題,也解決了物件識別的問題。
構造函式與工廠模式的不同之處在於:
當使用構造函式並 new 它時,後台其實執行了 new Object(),而函式體內的 this 就代表 new Object() 出來的物件。
最後補充幾個實用要點: