2

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('Duplicate');
    }
}

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

Or should I use this code:

function Shape() {
}

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

function Circle() {
}

Circle.prototype = Object.create(Shape.prototype);
adiga
  • 34,372
  • 9
  • 61
  • 83
Barzhalu
  • 35
  • 4
  • that depends on how you want it to behave. If you put things outside a function then they'll run straight away. If you put them inside a function they'll run when you call that function. The second one appears to make more sense but... – ADyson Jul 04 '19 at 09:50
  • 2
    The second approach – adiga Jul 04 '19 at 09:50
  • @ADyson when is the first approach useful? – adiga Jul 04 '19 at 09:51
  • @adiga that's for the OP to decide, surely? If they want to put things in functions that's up to them, depends what they're trying to do. – ADyson Jul 04 '19 at 09:51

1 Answers1

2

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
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143