通过javascript继承

zer*_*ero 2 javascript inheritance prototype

我一直在试验javascript的原型继承,并且遇到了一些可能可以解释的东西.

function dinner(food,drink){
   this.food=food;
   this.drink=drink;

}
dinner.prototype.desert=function(){
var x = this.food;

return x.split(' ')[0]+' Ice Cream Float';
}
function superSupper(steak){
    this.steak=steak;
}
superSupper.prototype= new dinner();
superSupper.prototype.constructor=superSupper;
var x = new superSupper('corn','beet juice')
x.grub='beef';
x.clams = 'nope';
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我正在制作一个新的construtor"superSupper"并使其继承晚餐.当在console.log中查看此内容时,我看到:

superSupper
clams: "nope"
grub: "beef"
steak: "corn"
__proto__: dinner
constructor: function superSupper(steak){
drink: undefined
food: undefined
__proto__: dinner
Run Code Online (Sandbox Code Playgroud)

我如何获得我现在从晚餐中继承的饮料和食品?

ps尝试这个:"x.food ='some string'"只在superSupper实例中创建一个名为food的新属性,但不为继承的food属性赋值.

Nem*_*moy 5

你必须修改superSupper一下:

function superSupper(steak){
    // calling superclass constructor
    dinner.apply(this, arguments);
    this.steak=steak;
}
Run Code Online (Sandbox Code Playgroud)