You are creating a new Cheese
instance, and the argument n
is never used or assigned to the Cheese
instance variable this.n
, because that logic is only used on the Food
constructor.
You can do a couple of things:
1 . Apply the Food
constructor inside the Cheese
function, using the arguments
object and the newly created context (this
).
function Food(n) {
this.n=n;
}
function Cheese(n) {
Food.apply (this, arguments);
alert(this.n);
}
new Cheese('paramesian');
2 . Repeat the Food
constructor logic (this.n = n
) on the Cheese
constructor function:
function Food(n) {
this.n=n;
}
function Cheese(n) {
this.n = n;
alert(this.n);
}
Cheese.prototype = new Food();
new Cheese('paramesian');
3 . Use another technique, like power constructors:
function food (n) {
var instance = {};
instance.n = n;
return instance;
}
function cheese (n) {
var instance = food(n);
alert(instance.n);
return instance;
}
cheese('parmesian');
cheese('gouda');
4 . Yet another option, prototypal inheritance:
// helper function
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F () {}
F.prototype = o;
return new F();
};
}
var food = {
n: "base food",
showName : function () { alert(this.n); }
};
var cheese1 = Object.create(food);
cheese1.n = 'parmesian';
cheese1.showName(); // method exists only in 'food'