Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Efficiently creating JavaScript objects: closures versus prototypes

DZone's Guide to

Efficiently creating JavaScript objects: closures versus prototypes

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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.

 

From http://www.2ality.com/2011/02/efficiently-creating-javascript-objects.html

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}