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