0

Lets say I have a class:

function Dog(name) {
    this.name = name; 
}
Dog.prototype = {
    constructor: Dog
}

I would like to add some methods to that class, but I'm confused where I should add them, to the constructor itslef, or to the prototype of that class.

for example I can do:

  function Dog(name) {
        this.name = name;
        this.bark = function() { 
            console.log(this.name + ' barked!');
        }
    }

Or I can alternatively do this:

function Dog(name) {
        this.name = name; 
    }
    Dog.prototype = {
        constructor: Dog,
        bark: function() {
            console.log(this.name + ' barked');
        }
    }

What are the differences between the 2 options? which one is better? and which situations should I use each one?

Sidenote: I am aware this question is basic enough to likely have duplicates, but I cannot find any simillar posts, maybe I am constructing the question wrong.

  • If you want to use the function more than once, add it in the constructor otherwise in the prototype. – Mario Jul 12 '18 at 16:28
  • It depends, do you want every `Dog` to share a function where changing the function changes the function for every `Dog` or do you want each `Dog` to have it's own function? "Which one is better" is up to use case. – zero298 Jul 12 '18 at 16:28
  • 1
    Setting the member method in `Dog.prototype` is typically what you want. If you initialize it in the constructor, each new instance of `Dog` creates a scoped copy of `bark`, which means you are not taking advantage of the features of prototypal inheritance such as lower memory usage. Also with V8 optimizations, accessing properties such as `bark` from a prototype object instead of an own property is usually faster. – Patrick Roberts Jul 12 '18 at 16:41

0 Answers0