i've been experimenting with javascript's prototypal inheritance and have come across something that perhaps can be explained.
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';
in the above code i'm making a new construtor "superSupper" and making it inherit from dinner. when this is viewed in a console.log i see this:
superSupper
clams: "nope"
grub: "beef"
steak: "corn"
__proto__: dinner
constructor: function superSupper(steak){
drink: undefined
food: undefined
__proto__: dinner
how do i access the drink and food properties that i have now inherited from dinner?
p.s. trying this: "x.food='some string'" only creates a new property in the superSupper instance called food, but does not assign a value to the inherited food property.
1 Answer 1
You have to modify your superSupper a bit:
function superSupper(steak){
// calling superclass constructor
dinner.apply(this, arguments);
this.steak=steak;
}
8 Comments
apply and call can be used to execute a function in the scope of another object. So here dinner will be executed in the scope of superSupper, hence this inside dinner at this point refers to superSupper and food and dinner becomes property of superSupper
superSupperinstances will have that property set, since the inheriteddinnerinstance is shared.dinnerinstance you created is set as the prototype ofsuperSupper, so if you set a property on thatdinnerinstance, allsuperSupperinstances will have that property set. If you want to set it on a per-superSupper-instance basis then I don't think you want to alter the inherited property.hasOwnPropertyallows to distinguish, is property defined in certain instance, or one of its prototypes.