简体   繁体   English

超级原型继承

[英]Super in prototypal inheritance

I am not sure what the right way to handle a "super" object in prototypal inheritance (as described by Douglas Crockford) should be. 我不确定在原型继承中如何处理“超级”对象的正确方法(如道格拉斯·克罗克福德(Douglas Crockford)所述)。 Currently I am using this.__proto__ , which leads to weird behavior when creating new objects. 目前,我正在使用this.__proto__ ,这在创建新对象时导致奇怪的行为。 Here is a simple example. 这是一个简单的例子。

var Animal = { talk: function() { return "I am an animal"}}
var Cat = Object.create(Animal);                            
Cat.talk = function(){return "I am a cat. " + this.__proto__.talk()}; 
var myCat = Object.create(Cat)
console.log(myCat.talk());

What I want the final output to be is "I am a cat. I am an animal." 我希望最终的输出是“我是猫。我是动物”。 Instead what I get is "I am a cat. I am a cat. I am an animal.". 相反,我得到的是“我是猫。我是猫。我是动物”。 This makes perfect sense since the prototype of myCat is Cat, not animal! 因为myCat的原型是猫,而不是动物,所以这很合理。

How do I deal with this behavior to replicate the inheritance from other languages that I know and love? 我该如何处理这种行为,以复制我所认识和喜爱的其他语言的继承?

Update 1/5/2015 I gave up on prototypal inheritance. 2015年 1月5日更新我放弃了原型继承。 One of these days I'll just switch to typescript I think... 这些日子之一,我只是切换到我认为的打字稿...

You should call the Animal's talk function, but pass your cat in for the thisArg : 您应该调用Animal的talk函数,但是将您的猫传递给thisArg

Animal.talk.call( this );

All together: 全部一起:

var Animal = { talk: function() { return "I am an animal"}}
var Cat = Object.create(Animal);                            
Cat.talk = function(){return "I am a cat. " + Animal.talk.call( this )}; 
var myCat = Object.create(Cat)
console.log(myCat.talk());

you will need explicitly mention Animal as Cat 's parent 您需要明确提及AnimalCat的父母

var Animal = { talk: function() { return "I am an animal"}}
var Cat = Object.create(Animal);           
Cat.parent = Animal;    //so that you can invoke its method later
Cat.talk = function(){return "I am a cat. " + this.parent.talk.call(this)}; 
var myCat = Object.create(Cat);

Other than this I don't see how you will do this without specifically referring Animal class while defining Cat.talk . 除此之外,在定义Cat.talk如果不特别引用Animal类,我将看不到如何Cat.talk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM