Re: [問題] 有關JavaScript繼承問題
※ 引述《Chansamo (Chansamo)》之銘言:
: 奇摩知識好讀版
: http://ppt.cc/klRb
: 程式碼如下,
: function GrandFather(){
: this.g1="";
: this.g2="";
: };
: function Father(){
: this.p3="";
: this.p4="";
: };
: function Child(){
: this.c5=c5;
: };
: Father.prototype=new GrandFather();
: Child.prototype=new Father();
: document.write(Child.prototype.constructor);
: document.write(Child.prototype.prototype.constructor);
: 現在我正在練習javascript的繼承問題,
: 目前是想做兩層的繼承
: 雖然單從繼承屬性空間的概念上來說,
: 繼承的結果是成功的,
: 但依照原型鏈以及下面
: Father.prototype=new GrandFather();
: Child.prototype=new Father();
: 這兩行來看,
: 若我執行
: document.write(Child.prototype.constructor);\\Father function(詳細構造器)
: document.write(Child.prototype.prototype.constructor);\\GrandFather function(
: 詳細構造器)
: 結果應該是分別指向
: 但真正的執行結果卻是
: document.write(Child.prototype.constructor);\\GrandFather function(詳細構造器)
: document.write(Child.prototype.prototype.constructor);\\錯誤
: 後來我查firefox的firbug查詢結果如下圖
: http://ppt.cc/PuJ2
: 其指向之父類別皆為GrandFather,
: 為何Child的第一層prototype沒有指向Father而是指向GrandFather呢?
: 以及若要修正應該要如何實做呢?
: 還請各位大大賜教。
function(){}
會產生一對物件,一個 function object 跟一個 prototype object。
prototype object 的 constructor property 會指向 function object。
function object 的 prototype property 會指向 prototype object。
new <function object> 會產生一個新物件,
新物件的 property lookup chain 最前端是自己本身,
再往上是 function object 的 prototype object,
而這個新物件本身並不具備 constructor property,
lookup 到的 constructor property 是 prototype object 的。
另 function object 本身並不在新物件的 property lookup chain 裡面。
所以以下一共產生六個 object,
function A(){}
function B(){}
function C(){}
A, A.prototype。// A.prototype.constructor === A
B, B.prototype。// B.prototype.constructor === B
C, C.prototype。// C.prototype.constructor === C
B.prototype = new A
則是先產生一個新物件,並且讓 B 的 prototype property 指向這個物件,
即是說 B 原本的 prototype object 被一個 A 的 instance 取代掉了。
B.prototype.constructor 會 lookup B.prototype 的 constructor property,
而 B.prototype 只是個 A 的 instance,本身並不具備 constructor property,
於是會再往上,查到 A.prototype 的 constructor property。
所以 B.prototype.constructor 會等於 A,因此在取代原本的 prototype 之後,
會 reset prototype 的 constructor property,很多 library 都會這樣寫。
Closure Library goog.inherit() http://ppt.cc/G@2J
MooTools Class() http://ppt.cc/x6TS
Prototype Class.create() http://ppt.cc/caux
這樣就可以理解為什麼 Child.prototype.constructor === GrandFather
至於 Child.prototype 則是一個單純的 Father instance,
前面說過 prototype 是 function object 的 property,
一個單純的 Father instance 並沒有這個 property,
再往上 lookup 也沒有,結果就是 error。
--
Oni devas ami animalojn. Ili estas tiel bongustaj.
One should love animals. They are so tasty.
每個人都應該愛動物,他們是如此美味。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 175.180.46.115
推
02/18 17:28, , 1F
02/18 17:28, 1F
→
02/18 17:29, , 2F
02/18 17:29, 2F
→
02/18 17:29, , 3F
02/18 17:29, 3F
→
02/18 17:29, , 4F
02/18 17:29, 4F
→
02/18 17:30, , 5F
02/18 17:30, 5F
→
02/18 17:30, , 6F
02/18 17:30, 6F
→
02/18 17:55, , 7F
02/18 17:55, 7F
推
02/18 18:13, , 8F
02/18 18:13, 8F
→
02/18 18:14, , 9F
02/18 18:14, 9F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):