進階-再講prototype

Prototype主要可以用來做/模擬傳統物件導向的繼承 inheritance

參考:

  1. [重要文章]Inheritance and the prototype chain, 使用 Object.create去建立一個新物件並且其prototype為傳進去的物件.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

var a = ["yo", "whadup", "?"];
// Arrays inherit from Array.prototype
// a ---> Array.prototype ---> Object.prototype ---> null

function f(){
  return 2;
}
// f ---> Function.prototype ---> Object.prototype ---> null

重點Notes:

  1. someobject.[[Prototype]] 等價於 物件的__proto__(deprecated). 但someobject.[[Prototype]]Function物件裡的.prototype不一樣. 見上面Inheritance and the prototype chain的說明.

  2. 不管是property或是method, access時若果當前type沒有找到此property/method, 都會往它的prototype指到的物件去找,遞迴的一直找到為止/或找到Object都沒有

  3. 為什麼常見自訂object type的method要用Car.prototype.autopilot此寫法,是因為在new Car()時, 它會copy這個Car(<-一function object)的prototype到新建的prototype property.

  4. 第4點補充: var g = new Graph(); g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.

  5. Object.create的概念

以下是各種不同使用.prototype來做繼承的examples. example-2 & example-3應該比較像是其他物件導向語言裡的繼承.

example-1: 使用 Object.create(某物件);並且繼承的人可以改到obj的property. 但會需要注意如下case的情形.

example-2: 使用 Object.create(某Function/type.prototype);

2-i 這篇有提到 多型polymorphism & factory pattern http://stackoverflow.com/questions/34525517/angularjs-how-to-achieve-polymorphism-dependency-injection-best-practices

2-ii 這篇有提到 多型polymorphism http://stackoverflow.com/questions/9850892/should-i-use-polymorphism-in-javascript

example-3: 不使用Object.create, 直接指定某Function/Type其Prototype, prototype = new Product()做到類似Object.create繼承的效果 https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Last updated