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