Why put methods on the prototype of a class instead of declaring them in the constructor?

136 views Asked by At

I'm trying to learn more about prototypal inheritance and I'm a little confused about the difference between adding methods to the prototype and adding them to the instance. Why would I do one over the other?

Prototype method:

function Foo() {}
Foo.prototype.doBar = console.log.bind(console, 'Did bar!');
var foo = new Foo();
foo.doBar(); // prints "Did bar!"

Instance method:

function Foo() {
  this.doBar = console.log.bind(console, 'Did bar!');
}
var foo = new Foo();
foo.doBar(); // prints "Did bar!"

What is the advantage of putting my methods on the prototype? Is there ever a time when it makes more sense to declare the method on the instance via the constructor?

2

There are 2 answers

1
idoberko2 On BEST ANSWER

Declaring methods via the constructor has performance implications. For each newly created instance, JS interpreter will have to read the functions code all over again.

Generally you want your constructor to be as light as possible, so it's a good thumb rule to always declare prototype methods and not via the constructor.

1
oscargilfc On

Internally is the same.

You use prototype when you are editing an object previously declared, that could be in an external library or something like that.

Is easier to edit the prototype than look for the original constructor declaration and modify the code there.

Also if you want to use the original declaration and then change it you can use prototype, but that's not recommended, is better to create a different "class" to avoid confusion.