12
I’m having doubts about creating instance variables in a Javascript constructor class/function. I have read in several places that the declaration of an instance variable is made within the class body as in the example below:
function Spam() {
this.foo = "foo"
}
But I realized I can also declare the variable in prototype
class as in the example below:
Spam.prototype.bar = "bar";
And in the end I end up getting the same result:
var mySpam = new Spam();
mySpam.foo // => "foo": declarado no corpo da classe
mySpam.bar // => "bar": declarado no prototype da classe
What is the difference between the two methods of declaring an instance variable?
Is there a problem with "hiding the prototype"? As far as I know, the principle behind prototypic inheritance (as opposed to classical inheritance) is precisely to take an existing object, well characterized, and state "that other object looks like that, the differences are x, y and z". (although I recognize that in practice this is not always used this way)
– mgibsonbr
@mgibsonbr, no, no problem (Duck Typing is for that same). I only stressed in the answer because, for those who come from another language (ex: Static in Java or C#), it may not be so obvious the difference.
– talles
Just clarifying in case someone gets confused, in
mySpam2.bar = "baz";
what will be hidden is not the entire prototype of the object, but only the propertybar
.– bfavaretto