DIV CSS 佈局教程網

JavaScript 基於原型的繼承入門教程
編輯:JavaScript基礎知識     

多數編程語言都有類與對象,一個類可以繼承另一個類。而 JavaScript 的繼承是基於原型的(prototype-based)——它沒有類,取而代之的是一個對象繼承另一個對象。

1. 繼承與 __proto__

當對象 rabbit 繼承了另一個對象 animal,這意味著 rabbit 上會有一個特殊屬性:rabbit.__proto__ = animal。訪問 rabbit 時,如果解釋器在 rabbit 自身找不到該屬性,就會沿著 __proto__ 鏈往上到 animal 中尋找。

注意 __proto__ 僅在 Chrome 和 Firefox 中可直接訪問:

var animal = { eats: true }
var rabbit = { jumps: true }
rabbit.__proto__ = animal // inherit

alert(rabbit.eats) // true

eats 是從 animal 中取得的。如果 rabbit 自身已有該屬性,就不會再去查原型:

var animal = { eats: true }
var fedUpRabbit = { eats: false}
fedUpRabbit.__proto__ = animal

alert(fedUpRabbit.eats) // false

父對象上也可以放函數,子對象同樣能訪問:

var animal = {
  eat: function() {
    alert( "I'm full" )
    this.full = true
  }
}
var rabbit = {
  jump: function() { /* something */ }
}
rabbit.__proto__ = animal

執行 rabbit.eat() 時分兩步:解釋器先在 rabbit 上找 eat,沒有就沿 rabbit.__proto__ 往上,在 animal 中找到;然後函數以 this = rabbit 運行。this 的值與 __proto__ 完全無關,因此 this.full = true 是寫在 rabbit 上的。

這正是繼承的精髓:對象調用了父層的函數,但 this 仍指向對象本身。被 __proto__ 引用的對象被稱作原型(prototype),animal 就是 rabbit 的原型。

讀時查找,不是寫時。讀取 this.prop 時,解釋器會沿原型鏈查找;而賦值 this.prop = value 時沒有查找的必要,屬性會直接寫到對象自身。delete obj.prop 同理,只刪自身屬性,原型上的同名屬性不受影響。

補充一個容易混淆的點:本文所說的 __proto__,在規範文檔中被寫作 [[Prototype]]。雙方括號很重要,因為還存在另一個叫 prototype 的屬性。

2. Object.create 與 Object.getPrototypeOf

__proto__ 是非標準的,由 Chrome/Firefox 提供訪問,其他瀏覽器並不可見。現代瀏覽器(IE9 及以上)提供了兩個標準方法來處理原型:

Object.create(proto[, props])

用給定的原型創建一個空對象:

var animal = { eats: true }
rabbit = Object.create(animal)

alert(rabbit.eats) // true

對象建好後再往上加屬性:

var animal = { eats: true }
rabbit = Object.create(animal)
rabbit.jumps = true

第二個參數 props 是可選的,用於同時定義新對象的屬性;這裡關注的是繼承,故暫且略過。

Object.getPrototypeOf(obj) 返回 obj.__proto__ 的值。它是標準方法,可以在無法直接訪問 __proto__ 的瀏覽器中使用:

var animal = { eats: true }
rabbit = Object.create(animal)

alert( Object.getPrototypeOf(rabbit) === animal ) // true

現代瀏覽器允許讀取 __proto__,但不允許設置。

3. 用構造函數設置原型

有一種跨瀏覽器都可行的方案,那就是使用構造函數——記住,任何函數配上 new 關鍵字都能構造對象。

function Rabbit(name) {
  this.name = name
}
var rabbit = new Rabbit('John')

alert(rabbit.name) // John

new 操作會把構造函數的原型設置到新對象的 __proto__ 上。看看它的原理,比如讓 Rabbit 繼承 animal:

var animal = { eats: true }

function Rabbit(name) {
  this.name = name
}
Rabbit.prototype = animal

var rabbit = new Rabbit('John')

alert( rabbit.eats ) // true,因為 rabbit.__proto__ == animal

Rabbit.prototype = animal 的字面含義就是:對所有由 new Rabbit 創建的對象,設 __proto__ = animal。

4. 跨瀏覽器的 Object.create(proto)

Object.create(proto) 之所以強大,是因為它允許直接從給定對象繼承。可以用下面這段代碼模擬:

function inherit(proto) {
  function F() {}
  F.prototype = proto
  return new F
}

inherit(animal) 與 Object.create(animal) 完全等價:返回一個空對象,且 object.__proto__ = animal。

var animal = { eats: true }
var rabbit = inherit(animal)

alert(rabbit.eats) // true
alert(rabbit.hasOwnProperty('eats')) // false,來自原型

逐行看它為何成立:

function inherit(proto) {
  function F() {}      // (1)
  F.prototype = proto  // (2)
  return new F         // (3)
}

(1)創建了一個不向 this 設置任何屬性的新函數,因此 new F 會得到一個空對象;(2)把 F.prototype 設為 proto;(3)new F 創建的空對象,其 __proto__ 即 F.prototype。於是得到一個繼承 proto 的空對象。

這個函數在各類庫和框架中廣泛可見。它也提供了一種優雅的解法:假設你的函數接收一個帶 options 的對象:

/* options contains menu settings: width, height etc */
function Menu(options) {
  // ...
}

你想改寫其中某些值:

function Menu(options) {
  options.width = options.width || 300 // set default value
  // ...
}

但直接改參數可能產生意外後果,因為 options 在外部代碼中還在被使用。一個常規辦法是克隆 options,把所有屬性複製到新對象再改。用繼承可以寫得更省事:

function inherit(proto) {
  function F() {}
  F.prototype = proto
  return new F
}

function Menu(options) {
  var opts = inherit(options)
  opts.width = opts.width || 300
  // ...
}

所有操作只作用於子對象,Menu 執行完畢後,外部代碼拿到的仍是未被修改的 options。這裡 delete 的行為值得留意:如果 width 是原型上的屬性,delete opts.width 不會有實際效果。

5. hasOwnProperty

所有對象都有 hasOwnProperty 方法,用來判斷某屬性是對象自身所有還是來自原型。

function Rabbit(name) {
  this.name = name
}
Rabbit.prototype = { eats: true }

var rabbit = new Rabbit('John')

alert( rabbit.hasOwnProperty('eats') ) // false,在原型上
alert( rabbit.hasOwnProperty('name') ) // true,在對象自身

6. 遍歷時區分自有屬性與繼承屬性

for..in 會輸出一個對象的所有屬性,包括自身的與原型的:

function Rabbit(name) {
  this.name = name
}
Rabbit.prototype = { eats: true }

var rabbit = new Rabbit('John')

for(var p in rabbit) {
  alert (p + " = " + rabbit[p]) // 輸出 name 和 eats
}

配合 hasOwnProperty 就能過濾出自身屬性:

function Rabbit(name) {
  this.name = name
}
Rabbit.prototype = { eats: true }

var rabbit = new Rabbit('John')

for(var p in rabbit) {
  if (!rabbit.hasOwnProperty(p)) continue // 過濾掉 eats
  alert (p + " = " + rabbit[p]) // 只輸出 name
}

7. 小結

JavaScript 通過一個特殊的 __proto__ 屬性實現繼承。訪問屬性時若對象自身找不到,就沿原型鏈繼續向上;對函數屬性而言,this 指向調用它的對象,而不是原型。賦值 obj.prop = value 與 delete obj.prop 都只作用於對象自身。

原型的管理方式:Chrome 和 Firefox 可直接訪問 __proto__;多數現代瀏覽器支援只讀的 Object.getPrototypeOf(obj);Object.create(proto) 可用給定原型生成空的子對象,也可以用前面那個 inherit 函數達到同樣效果。

輔助手段:for..in 遍歷對象全部屬性(含繼承而來);obj.hasOwnProperty(prop) 用來判斷屬性是否歸屬於對象自身。

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