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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}