進階-再講prototype
Last updated
Last updated
Prototype主要可以用來做/模擬傳統物件導向的繼承 inheritance
參考:
Function.prototype
[重要文章]Inheritance and the prototype chain, 使用 Object.create
去建立一個新物件並且其prototype為傳進去的物件.
重點Notes:
someobject.[[Prototype]]
等價於 物件的__proto__
(deprecated). 但someobject.[[Prototype]]
跟Function物件裡的.prototype
不一樣. 見上面Inheritance and the prototype chain的說明.
不管是property或是method, access時若果當前type沒有找到此property/method, 都會往它的prototype指到的物件去找,遞迴的一直找到為止/或找到Object都沒有
為什麼常見自訂object type的method要用Car.prototype.autopilot
此寫法,是因為在new Car()時, 它會copy這個Car(<-一function object)的prototype到新建的prototype property.
第4點補充: var g = new Graph();
g.[[Prototype]]
is the value of Graph.prototype
when new Graph() is executed.
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
2-ii 這篇有提到 多型polymorphism
example-3: 不使用Object.create
, 直接指定某Function/Type其Prototype, prototype = new Product()
做到類似Object.create
繼承的效果