亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

求高手回答原型繼承的問題

求高手回答原型繼承的問題

眼眸繁星 2018-11-13 17:19:57
function Parent(firstName,color){    this.firstName = firstName;    this.color = color;    this.showName = function (){        console.log("我家姓氏:"+this.firstName);    }}Parent.prototype.showAll=function(){    console.log("姓:"+this.firstName+"\n"+"喜愛的顏色:"+this.color);}function Child(myName,age,firstName,color){    this.myName = myName;    this.age = age;     Child.prototype=Parent.prototype;    Parent.call(this,firstName,color);}/*Child.prototype=Parent.prototype;*/var c = new Child("帥",23,"孫","粉色");var d=new Parent("孫","粉色");d.showAll();//姓:孫            //喜愛的顏色:粉色c.showAll();//error c.showAll is not a functioncall對象冒充為什么this不能獲得構造函數Parent的原型?還有Child.prototype=Parent.prototype;寫在Child函數里不行,為什么拿出來寫在window環境就可以?
查看完整描述

1 回答

?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

題主:代碼可以再捋一捋

Child.prototype=Parent.prototype    // Parent.prototype指向的是Object

Child.prototype=Parent    //該是這樣吧

第一個問題:this不能獲得構造函數Parent的原型

function Child() 定義一個函數,使用var c = new Child() this的指向為對象c,就沒指向 Parent,不過你使用c.showName(),還是能獲取到的,因為原型繼承.

第二個問題:寫在Child函數里不行,為什么拿出來寫在window環境就可以?

寫在函數里面也行的, this.prototype=Parent;
一個new做了以下幾件事情:

  1. 創建一個新的對象

  2. 查找Childprototype上的所有方法、屬性,復制一份給創建的對象

  3. 將構造函數Child內部的this指向創建的對象

  4. 創建的對象的__proto__指向Childprototype

  5. 執行構造函數

  6. 返回新創建的對象給變量c

寫在內部就是在第五部寫入,寫在外部是在第四部寫入,故與內外無關。


查看完整回答
反對 回復 2018-12-05
  • 1 回答
  • 0 關注
  • 447 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號