Efficiently creating JavaScript objects: closures versus prototypes
In
“
Closure Versus Prototypal Pattern Deathmatch”, Brendan Eich examines the question whether, when creating objects, the closure pattern or the prototypal pattern is more efficient.
The code below shows the closure pattern for creating objects.
function ClosurePattern() {
this.someMethod = function someMethod() {
console.log('foo');
}
}
var closurePattern = new ClosurePattern();
The code below shows the prototypal pattern for creating objects.
function PrototypalPattern() {}
PrototypalPattern.prototype = {
someMethod: function () {
console.log('foo');
}
}
var prototypalPattern = new PrototypalPattern();
Summary of the post:
- Advantages of the closure pattern:
- You can encapsulate private data.
- Advantages of the prototypal pattern:
- Going up the prototype chain is highly optimized in most JavaScript engines and happens fast.
- You save space, because no closure has to be created and someMethod is shared between objects (as opposed to added to each object).
- I also find it more readable: Instance variables are defined in the constructor, instance methods are defined in the prototype.
- Easier to analyze for tool builders. I feel for them, as they have to handle all of those JavaScript patterns and APIs out there.
Note that things will change in the not-too-distant future, as
ECMAScript Harmony will bring many changes in this area.