繼承 子類的原型指向父類的例項

2021-09-25 12:28:42 字數 764 閱讀 4129

//子類的原型指向父類的例項

//建構函式 animal

function animal()

} //在animal的原型上有乙個eat方法

animal.prototype.eat=function()

//cat建構函式

function cat()

//把cat的原型指向了animal的例項

//子類的原型指向父類的例項

cat.prototype=new animal()

//tom為cat的例項 ,tom是可以用構造它的建構函式上原型的方法,

//但是cat的原型指向了 animal的例項,進而用了animal原型上的方法,改變了原型指向,破壞了原型鏈

//constructor構造器,指回不了建構函式cat

var tom=new cat()

//讓他指回cat,

cat.prototype.constructor=cat//cat的constructor就值回cat了

tom.eat("fish")//無法傳參,傳的沒用

tom.say()

console.log(tom);

console.log(tom instanceof animal)

console.log(tom instanceof cat);

console.log(cat.prototype.constructor);//構造器指向了animal,本該指向建構函式自己

python子類如何繼承父類的例項變數?

型別1 父類和子類的例項變數均不需要傳遞 classa object def init self self.name cui defget name self return self.name class b a def init self super b,self init self.age 12...

python子類如何繼承父類的例項變數?

型別1 父類和子類的例項變數均不需要傳遞 class a object def init self self.name cui def get name self return self.name class b a def init self super b,self init self.age ...

父類引用指向子類物件

要理解多型性,首先要知道什麼是 向上轉型 我定義了乙個子類cat,它繼承了animal類,那麼後者就是前者是父類。我可以通過 cat c new cat 例項化乙個cat的物件,這個不難理解。但當我這樣定義時 animal a new cat 這代表什麼意思呢?很簡單,它表示我定義了乙個animal...