Question

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.

Was it helpful?

Solution

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?.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top