I've been recently experimenting with prototyping in javascript and I can't figure out why the following code doesn't work. What I would like to do is create a new instance of cheese with parameter n.
function food(n) {
this.n=n;
}
function cheese(n) {
alert(this.n);
}
cheese.prototype=new food;
new cheese('paramesian');
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters. JavaScript does not generate any errors in such a case.
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With