I can declare methods of an object in two ways:
The first way uses the self=this idiom.
function SelfIdiomExample(name){
var self = this;
self.sayHello = function (name){
alert("Hello, "+name);
}
}
Which is useful when you need a reference to the object in a method (for example if the method will be passed as a callback). The other way is to do it by modifying the prototype:
function PrototypeModExample(){
//pass
}
PrototypeModExample.prototype.sayHello = function(name){
alert("Hello, "+name);
}
Both have the same result:
var sieg = new SelfIdiomExample();
var pmeg = new PrototypeModExample();
sieg.sayHello("Barnaby");
pmeg.sayHello("Josephine");
While I understand the use case for the self=this idiom, I am wondering:
Is there a performance penalty to using the methods created in the constructor versus methods created on the prototype?
Well this here:
Is not something has performance implications at all. It’s wicked fast as it’s simply accessing a local variable. Even from nested funcitons, this is a very fast operation in JavaScript.
However, methods created in the constructor versus methods created on the prototype has a huge performance difference.
In this example:
Every instance of the constructor gets access to the same function objects. Which can be proved by using the
===operator to compare the function objects on two instances. It will only returntruewhen they are the same object. So globally we now have 2 instances, but they share one function object for the implementation of thesayHellomethod. This means that function is already setup and created when you want to make a new instance.In other words, for all instance
obj.sayHellopoints to the same function object, which was created before any instances existed at all.But this on the the other hand:
Works differently. Now we see that the
===comparison is false. That’s because a new function object was created for each instance. Creating this function takes time (it needs to be parsed) and memory (this unique version of that function needs to be stored). So when creating lots of these instances, this method will be both slower and consume more memory.In other words, for all instance
obj.sayHellopoints to a unique function object which was created when the instance itself was created.So usually, the prototype method is preferred. Especially in cases where a large number of instance might exist, since each instance can share function objects for it’s methods.