// Case A
function Constructor() {
this.foo = function() {
...
};
...
}
// vs
// Case B
function Constructor() {
...
};
Constructor.prototype.foo = function() {
...
}
One of the main reasons people advise the use of prototypes is that .foo
is created once in the case of the prototype where as this.foo
is created multiple times when using the other approach.
However one would expect interpreters can optimize this. So that there is only one copy of the function foo
in case A.
Of course you would still have a unique scope context for each object because of closures but that has less overhead then a new function for each object.
Do modern JS interpreters optimise Case A so there is only one copy of the function foo
?