Over a million developers have joined DZone.

Efficiently creating JavaScript objects: closures versus prototypes

DZone's Guide to

Efficiently creating JavaScript objects: closures versus prototypes

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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() {
var closurePattern = new ClosurePattern();
The code below shows the prototypal pattern for creating objects.
    function PrototypalPattern() {}
PrototypalPattern.prototype = {
someMethod: function () {
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

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}