通过javascript继承

inheritance via javascript

本文关键字:继承 javascript 通过      更新时间:2023-09-26

我一直在尝试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';

在上面的代码中,我正在制作一个新的构造器"superSupper",并使其继承自dinner。当在控制台日志中查看时,我看到的是:

superSupper
clams: "nope"
grub: "beef"
steak: "corn"
__proto__: dinner
constructor: function superSupper(steak){
drink: undefined
food: undefined
__proto__: dinner

如何访问我从晚餐中继承的饮料和食物属性?

p.s.尝试这样做:"x.food=‘some string’"只在superSupper实例中创建一个名为food的新属性,但不为继承的food属性赋值。

您必须稍微修改superSupper

function superSupper(steak){
    // calling superclass constructor
    dinner.apply(this, arguments);
    this.steak=steak;
}