3

I saw some code defines the methods in the prototype this way:

function Class() {...}
(function() {
    this.method1 = function() {...};
    this.method2 = function() {...};
}).call(Class.prototype);

What is the benefit of this construct versus others? Here are some other examples:

function Class() {...}
Class.prototype = {
    method1: function() {...},
    method2: function() {...}
};

or

function Class() {...}
Class.prototype.method1 = function() {...};
Class.prototype.method2: function() {...};

or

function Class() {...}
Class.prototype = Object.create({...}, {...});
Class.prototype.constructor = Class;

the following I know is a bit less efficient in term of memory because each instance has its own copy of method1 and method2:

function Class() {
    var privateVar = 0;
    this.method1 = function() {...};
    this.method2 = function() {...};
}

of course the benefit of this construct is that the methods can access private variables.

cookie monster
  • 10,671
  • 4
  • 31
  • 45
unional
  • 14,651
  • 5
  • 32
  • 56
  • First and third are identical, as are the second and fourth assuming you pass `Object.prototype` in the fourth, and pass the methods with the same property descriptors. *(The fourth also adds the `.constructor` back in, and the second doesn't)*. The last doesn't use inheritance. The distinction between the first/third and the second/fourth is minimal. – cookie monster May 09 '14 at 03:50
  • I'd say no *substantial* benefit to any of the first four examples since they're almost identical. More important is to understand what the syntax is doing so that you can make that determination for yourself. – cookie monster May 09 '14 at 03:56

1 Answers1

1

The snippets #1 and #3 do the same thing. The benefit of the first is that you don't need to repeat Class.prototype., and might even define static "class-local" variables. However, the usage of .call is unusal, mostly a simple parameter named proto or so is used:

function Class() {...}
(function(p) {
    p.method1 = function() {...};
    p.method2 = function() {...};
}(Class.prototype));

The difference between this assignment of individual properties and snippet #2 is covered in Defining a Javascript prototype.

What snippet #4 does is a little unclear do to your use {...}. However, Object.create is usually used for inheritance between classes.

The difference between prototype methods and instance-specific methods (snippet #5) is well-covered in Use of 'prototype' vs. 'this' in JavaScript?.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375