This seems like such a dumb question but…
If we have a constructor:
function Candy(name) {
this.name = name;
}
and we extend the prototype of this object Candy:
Candy.prototype.printName = function(name) {
console.log(this.name);
};
then we create a new object from the Candy constructor and run the inherited method for this new object:
var chocolate = new Candy("chocolate");
chocolate.printName();
It’s not clicking with me as to why we get chocolate as an output.
When we create the chocolate object from the constructor have we in essence done this:
var chocolate = new Candy();
chocolate.name = name;
and if so, why is it that when we run:
chocolate.printName();
with a blank argument, it spits out: “chocolate”?
Isn’t chocolate simply the name of the object that we built out of the Candy construcor?
As in, chocolate is not what we have assigned the chocolate.name parameter to be, but name is. Since we passed an empty argument field, why are we getting “chocolate” and not name back?
The parameter
namein theprintNamemethod is never used. To call the method with the signature that you specified, you would do like this:That would send the string
"Fudge"into the method as the parametername, but the parameter is ignored, and it still prints out the name that you specified for the object instead.Javascript allows you to call any function with any number of parameters. If you use too few parameters, the rest of the parameters will just have the value
undefined, and if you use too many parameters, they will be in theargumentscollection, but they will not be put in a parameter variable.So, if you call
chocolate.printName();, the parameternamewill have the valueundefined. If you callchocolate.printName(1,2,3), parameternamewill have the value1, and the other values would be available inside the function asarguments[1]andarguments[2].