3

Method 1:

Rectangle.prototype.getArea = function() {
     return this.length * this.width;
};

Method 2:

Rectangle.prototype = {
     getArea: function() {
          return this.length * this.width;
     }
};

What are the differences and advantages of each of the methods above?

  • 2
    Same as when working with a normal object, the second style destroys all existing contents of `prototype`. – DCoder May 27 '13 at 12:19
  • 4
    That's basically the same as `x += 10` vs `x = 10`. – georg May 27 '13 at 12:20
  • See also [Defining a Javascript prototype](http://stackoverflow.com/questions/17474390/defining-a-javascript-prototype) – Bergi Mar 10 '14 at 18:49

3 Answers3

4

The second one breaks the inheritance chain and removes all properties you would have added before to the prototype.

Let's see what I mean by "inheritance chain break" with this example :

function A(){}
A.prototype.a = function(){}
function B(){}
B.prototype = new A();
B.prototype.b = function(){}

an instance of B here inherits the a method.

But if you do

B.prototype = { b: function(){} }

then that's no longer the case.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

In the first case you are adding a new property to an existing object, in the second case you are overwriting Rectangle.prototype with a new value (object).

Overwriting the prototype has the following consequences:

  • Rectangle.prototype.constructor does not point to Rectangle anymore. When you use an object literal, it will point to Object instead. This can easily by solved by assigning

    Rectangle.prototype.constructor = Rectangle;
    
  • You potentially loose all existing properties on the prototype (unless you add them again, like with constructor).

  • Existing instances of Rectangle will not be affected by the change. They will still reference the old prototype and don't inherit the new methods/properties.

  • instanceof tests on existing instances (i.e. rect instanceof Rectangle) will fail, since instanceof compares prototypes and as mentioned in the previous point, existing instances keep their reference to the old prototype.

If you set up the prototype before you create any instances then you don't have to concern yourself with the last three points.

What are the differences and advantages of each of the methods above?

The only advantage of overwriting the prototype using an object literal is the more concise syntax. IMO it does not outweigh the disadvantages though.

You can use an object literal without overwriting the prototype by merging the two objects: How can I merge properties of two JavaScript objects dynamically?.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

If Rectangle.prototype is {}, there is no difference between the two methods.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194