Skip to content Skip to sidebar Skip to footer

Adding Prototype Methods Outside Vs Inside Of Constructor Function

I was learning prototype in JavaScript and wanted to ask you if the following code is correct: function Shape() { Shape.prototype.duplicate = function() { console.log('

Solution 1:

tl;dr: The prototype should be initialized outside the constructor.


The prototype object is something that should be initialized/created only once. Changing it inside the constructor means that every time a new instance is created, the prototype is changed one way or the other.

That kind of defeats the purpose of prototypes because they should be setup ones and shared across all instances (to "save" memory).

It's not so evident for Shape, but it becomes more evident for Circle:

function Shape() {
    Shape.prototype.duplicate = function() {
        console.log('Duplicate');
    }
}

function Circle() {
    Circle.prototype = Object.create(Shape.prototype);
}

var c1 = new Circle();
var c2 = new Circle();

console.log(
  Object.getPrototypeOf(c1) === Object.getPrototypeOf(c2),
  ':-O every Circle instance has its own prototype'
);

c1.duplicate();
// can't even call `c1.duplicate` because 
// `Circle.prototype = Object.create(Shape.prototype);` happens 
// *after* the first instance was created

Post a Comment for "Adding Prototype Methods Outside Vs Inside Of Constructor Function"