DIV CSS 佈局教程網

JavaScript 面嚮物件實戰:從工廠函數到原型鏈繼承的完整梳理
編輯:關於JavaScript     

寫 JavaScript 久了會發現,同一個需求往往有好幾種建立物件的方式,而它們在記憶體結構、方法共享與繼承能力上差別很大。這篇筆記把常見的幾種寫法從頭到尾排一遍,順便把原型鏈與繼承的坑都標出來。

一、工廠模式:最直覺的批量生產

function createPerson(name, age, job){
  var o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function(){
    alert(this.name);
  };
  return o;
}

var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");

person1.sayName(); // "Nicholas"
person2.sayName(); // "Greg"

思路很直白:函數內部開一個新物件,塞進屬性與方法,再把它回傳。問題也同樣直白——每呼叫一次就會重新產生一份 sayName,當物件數量多起來,重複的函數體散落在每個實例裡,既浪費記憶體也不好維護。

二、構造函數模式:new 到底做了什麼

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = function(){
    alert(this.name);
  };
}

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

alert(person1 instanceof Object);   // true
alert(person1 instanceof Person);   // true
alert(person1.constructor == Person); // true
alert(person1.sayName == person2.sayName); // false

用 new 呼叫時,引擎其實做了四件事:

  • 建立一個全新的空物件;
  • 把構造函數的作用域交給這個新物件,也就是讓 this 指向它;
  • 執行構造函數本體,完成屬性賦值;
  • 回傳這個新物件。

相比工廠模式,構造函數不必自己 return,而且實例與構造函數之間有 instanceof 與 constructor 這條可追溯的線索。但最後一行也提醒我們:方法依然是在函數體內定義的,兩個實例各有一份。

三、把構造函數當普通函數用

var person = new Person("Nicholas", 29, "Software Engineer");
person.sayName();          // "Nicholas"

Person("Greg", 27, "Doctor"); // 相當於掛到 window 上
window.sayName();          // "Greg"

var o = new Object();
Person.call(o, "Kristen", 25, "Nurse");
o.sayName();               // "Kristen"

不帶 new 呼叫時,this 會落到全域物件上,屬性就變成了 window 的成員;用 call 指定 this,屬性才會掛到指定物件。可見「構造函數」和「普通函數」在語法層面並沒有區別,差別完全來自呼叫方式。

四、把共用方法提到全域:解決了唯一性,卻弄髒了命名空間

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = sayName;
}

function sayName(){
  alert(this.name);
}

alert(person1.sayName == person2.sayName); // true

這樣一來所有實例共享同一個函數參照,唯一性問題解決了。但 sayName 被丟到全域,只能有一個,一旦頁面裡出現第二個需要同名方法的型別就會互相打架。實務上很少這麼寫。

五、原型模式:共享方法的正解

每個函數被建立時都會帶一個 prototype 屬性,它指向一個原型物件,而這個物件上的成員可以被該型別的所有實例共用。

function Person(){}

Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
  alert(this.name);
};

var person1 = new Person();
var person2 = new Person();

person1.sayName(); // "Nicholas"
alert(person1.sayName == person2.sayName);          // true
alert(Person.prototype.isPrototypeOf(person1));     // true

if (Object.getPrototypeOf) {
  alert(Object.getPrototypeOf(person1) == Person.prototype); // true
  alert(Object.getPrototypeOf(person1).name);                // "Nicholas"
}

如何理解原型

只要宣告一個函數,就會同時產生一個原型屬性指向原型物件。預設情況下原型物件上有一個 constructor,它是個指針,指回 prototype 所在的那個函數。

屬性的查找順序

讀取某個屬性時,引擎會做一次搜尋:先找實例本身,找到就回傳;找不到就沿著原型鏈往上找,直到鏈的末端。

person1.name = "Greg";
alert(person1.name); // "Greg"    來自實例
alert(person2.name); // "Nicholas" 來自原型

delete person1.name;
alert(person1.name); // "Nicholas" 又回到原型

六、hasOwnProperty:分辨屬性住在哪裡

這個方法繼承自 Object,只有在屬性確實存在於實例本身時才回傳 true。

alert(person1.hasOwnProperty("name")); // false
alert("name" in person1);              // true

person1.name = "Greg";
alert(person1.hasOwnProperty("name")); // true

delete person1.name;
alert(person1.hasOwnProperty("name")); // false
alert("name" in person1);              // true

in 操作符只要屬性能在實例或原型鏈上找到就回傳 true,兩者搭配使用就能判斷屬性的歸屬。

七、Object.keys 與 Object.getOwnPropertyNames

var keys = Object.keys(Person.prototype);
alert(keys); // "name,age,job,sayName"

var allKeys = Object.getOwnPropertyNames(Person.prototype);
alert(allKeys); // "constructor,name,age,job,sayName"

Object.keys() 只列出可列舉的自身屬性,因此不含 constructor;getOwnPropertyNames() 則不論是否可列舉,全部列出。這兩個方法需要較新版本的瀏覽器支援。

八、更簡潔的原型寫法,以及 constructor 被覆寫的陷阱

Person.prototype = {
  name: "Nicholas",
  age: 29,
  job: "Software Engineer",
  sayName: function(){ alert(this.name); }
};

var friend = new Person();
alert(friend.constructor == Person); // false
alert(friend.constructor == Object); // true

用字面量整體覆寫原型,等於丟掉了預設的 constructor,它會被還原成 Object。若在意這一點,可以手動補回去:

Person.prototype = {
  constructor: Person,
  name: "Nicholas",
  age: 29,
  job: "Software Engineer",
  sayName: function(){ alert(this.name); }
};

alert(friend.constructor == Person); // true

這個 constructor 屬性預設是不可列舉的,手動寫回去後它會變成可列舉,這是個容易被忽略的小副作用。

九、隨時補方法的自由

var friend = new Person();

Person.prototype.sayHi = function(){
  alert("hi");
};

friend.sayHi(); // "hi",即使 friend 早就建立好了

因為查找是執行期才發生的,原型上新增的方法對所有既有實例都立刻生效。

十、原生物件也能擴充

alert(typeof Array.prototype.sort);        // "function"
alert(typeof String.prototype.substring);  // "function"

String.prototype.startsWith = function(text){
  return this.indexOf(text) == 0;
};

alert("Hello world!".startsWith("Hello")); // true

技術上完全可行,但在正式專案裡更建議用工具函數或 polyfill 來實作,避免污染內建原型而與其他程式庫衝突。

十一、組合模式:構造函數管屬性,原型管方法

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.friends = ["Shelby", "Court"];
}

Person.prototype = {
  constructor: Person,
  sayName: function(){ alert(this.name); }
};

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

person1.friends.push("Van");
alert(person1.friends);             // "Shelby,Court,Van"
alert(person2.friends);             // "Shelby,Court"
alert(person1.friends === person2.friends); // false
alert(person1.sayName === person2.sayName); // true

這是最常用的組合:實例屬性放構造函數裡,各自獨立;方法放原型上,共用一份。既避開了原型共享引用型別的問題,也解決了方法重複建立的浪費。

十二、動態原型模式

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;

  if (typeof this.sayName != "function") {
    Person.prototype.sayName = function(){
      alert(this.name);
    };
  }
}

var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName();

把方法初始化包在判斷式裡,只在第一次建立實例時才寫入原型,兼顧了封裝與唯一性。

十三、寄生構造函數模式

function Person(name, age, job){
  var o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function(){ alert(this.name); };
  return o;
}

function SpecialArray(){
  var values = new Array();
  values.push.apply(values, arguments);
  values.toPipedString = function(){
    return this.join("|");
  };
  return values;
}

var colors = new SpecialArray("red", "blue", "green");
alert(colors.toPipedString()); // "red|blue|green"

它在函數內部建立並回傳另一個物件,因此返回的物件與外層構造函數之間沒有原型關係,instanceof 也就失去意義。適合在無法改寫既有構造函數的前提下,為特殊型別添加方法的場景。

十四、穩妥構造函數模式

function Person(name, age, job){
  var o = new Object();
  o.sayName = function(){
    alert(name); // 直接閉包外部參數,不依賴 this
  };
  return o;
}

var friend = Person("Nicholas", 29, "Software Engineer");
friend.sayName(); // "Nicholas"

不談 new、不談 this,除了物件自己開放的那些方法之外沒有任何入口。安全性最高,也最不靈活,通常用於沙箱或安全要求較高的環境。

十五、原型鏈繼承

function SuperType(){
  this.property = true;
}
SuperType.prototype.getSuperValue = function(){
  return this.property;
};

function SubType(){
  this.subproperty = false;
}

SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
  return this.subproperty;
};

var instance = new SubType();
alert(instance.getSuperValue());       // true
alert(instance instanceof SuperType);  // true
alert(instance instanceof SubType);    // true

核心就是把子型別的原型指向父型別的實例,於是搜尋鏈自然串了起來。子原型上可以新增方法,也可以覆寫繼承來的方法:

SubType.prototype.getSuperValue = function(){
  return false;
};
alert(instance.getSuperValue()); // false

但要特別小心兩件事。第一,用字面量重新賦值子原型,會把剛建立好的原型鏈整條丟掉:

SubType.prototype = {
  getSubValue: function(){ return this.subproperty; }
};
alert(instance.getSuperValue()); // 錯誤!原型鏈已斷

第二,原型上的引用型別屬性會被所有子實例共享:

function SuperType(){
  this.colors = ["red", "blue", "green"];
}
function SubType(){}

SubType.prototype = new SuperType();

var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); // "red,blue,green,black"

var instance2 = new SubType();
alert(instance2.colors); // "red,blue,green,black" —— 被連帶修改

十六、借用構造函數

function SubType(){
  SuperType.call(this); // 在子構造函數裡呼叫父構造函數
}

var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); // "red,blue,green,black"

var instance2 = new SubType();
alert(instance2.colors); // "red,blue,green" —— 各自獨立

透過 call 把父構造函數在新實例上執行一次,每個實例都拿到自己的一份屬性副本。缺點是方法必須定義在構造函數裡,無法共用原型方法。它也支援參數傳遞:

function SuperType(name){
  this.name = name;
}
function SubType(){
  SuperType.call(this, "Nicholas");
  this.age = 29;
}

var instance = new SubType();
alert(instance.name); // "Nicholas"
alert(instance.age);  // 29

十七、組合繼承

function SuperType(name){
  this.name = name;
  this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
  alert(this.name);
};

function SubType(name, age){
  SuperType.call(this, name); // 借用構造函數拿到實例屬性
  this.age = age;
}

SubType.prototype = new SuperType(); // 原型鏈拿到原型方法
SubType.prototype.constructor = SubType;

兩種方式各取所長:屬性靠借用構造函數保證獨立,方法靠原型鏈實現共用。這是 ECMAScript 裡最常被人推薦的繼承方式。

十八、原型式繼承

function object(o){
  function F(){}
  F.prototype = o;
  return new F();
}

var person = {
  name: "Nicholas",
  friends: ["Shelby", "Court", "Van"]
};

var anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob"); // 注意:friends 是共用參照

不必先建立型別,直接以既有物件為藍本產生新物件。ES5 之後可以直接用 Object.create() 達成同樣效果。

十九、寄生組合式繼承:目前最理想的方案

function object(o){
  function F(){}
  F.prototype = o;
  return new F();
}

function inheritPrototype(subType, superType){
  var prototype = object(superType.prototype);
  prototype.constructor = subType;
  subType.prototype = prototype;
}

function SuperType(name){
  this.name = name;
  this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
  alert(this.name);
};

function SubType(name, age){
  SuperType.call(this, name);
  this.age = age;
}

inheritPrototype(SubType, SuperType);

SubType.prototype.sayAge = function(){
  alert(this.age);
};

var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); // "red,blue,green,black"
instance1.sayName();     // "Nicholas"
instance1.sayAge();      // 29

var instance2 = new SubType("Greg", 27);
alert(instance2.colors); // "red,blue,green" —— 不受影響
instance2.sayName();     // "Greg"

它只呼叫父構造函數一次(用於設定屬性),並以父原型的一份淺拷貝作為子原型,既滿足了屬性獨立、方法共用,又避免了組合繼承多呼叫一次的開銷。理解原型鏈之後,這段十行不到的程式碼值得反覆讀幾遍。

以上就是這次整理的全部內容,後續還會持續補充筆記。

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