ciembor
ciembor

Reputation: 7337

Advantages of extending prototype instead of declaring whole object

When should I use first notation:

var object = {
    a: function() {
        // object.a method body
    },
    b: function() {
        // object.b method body
    },
    c: function() {
        // object.c method body
    },
};

and when the second one?

function Class() {};

Class.prototype.a = function() {
    // object.a method body
};

Class.prototype.b = function() {
    // object.b method body
};

Class.prototype.c = function() {
    // object.c method body
};

var object = new Class();

Upvotes: 1

Views: 135

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382132

The main advantage is that the functions are shared by all instances in second case, which makes the objects lighter. It explicitly defines the objects as instances of what is conceptually a class.

But the correct syntax is

function MyClass(){
}
MyClass.prototype.a = function(){
};
...
var o = new MyClass();

It also allows you to define an inheritance chain :

function OtherClass(){
}
OtherClass.prototype = new MyClass(); // makes OtherClass extend MyClass
OtherClass.prototype.b = function(){
};
...
var o2 = new OtherClass();

o2 has the functions of both OtherClass and MyClass.

The MDN gives more details in its Introduction to Object-Oriented JavaScript.

Upvotes: 2

Related Questions