Let's say I have this code:
(function(global) {
function Bar(foo) {
this.foo = foo;
return this;
}
Bar.prototype.getFoo = function() {
return this.foo;
};
Bar.prototype.setFoo = function(val) {
return (this.foo = val);
};
})(this);
What is the difference between creating functions like setFoo
with prototype
and just doing it like this:
function Bar(foo) {
this.getFoo = function() {
return this.foo;
};
}
I know what prototype is and what it means, I just can't figure out, why some people assign functions with prototype, because if I assign them with this, they will be available also every time I create a new instance of Bar.
If you have more than one instance of the "class" (using the term loosely), they all share the same prototype. So attaching things there is more light-weight, and it guarantees that they all have the same version (if that is what you want).
Think about it as instance fields vs class fields.
Prototypes can also be chained to allow for "inheritance" of fields.
The quick answer = function sharing + smaller memory footprint
When you're using
prototype.functionName
all instances share the same function (only one copy in memory), but if you usethis.functionName
in your constructor each instance has its own copy of the same function (exists multiple times in memory).Using
prototype
has two implications:Advanced - you can have both
You can also have both in which case the local copy has precedence over the prototype which means that you could do stuff like this:
An aside :
With prototypal inheritance, there's a fundamentel difference between own properties and inherited ones.
Sometimes this can be quite relevant.
A classic for loop that is often used, only checks for the 'own properties', taking this form :
When assigning to
this
, alle properties are own properties, making the hasOwnProperty check irrelevant.When you use
prototype
, the function is shared, when you assign the function tothis
, they are not. Instead, every instance will have its own copy of the funciton.