Defining prototype methods inside the constructor

This is a very bad idea, for a great number of reasons. A few of which are:

  1. Adding methods to the prototype in the constructor will cause the prototype method to be replaced for all instances, everytime you instantiate a new Dog.
  2. Calling Dog.prototype.bark() means that this will be Dog.prototype and not your instance of Dog, which can cause serious issues.
  3. this.bark = function () { Dog.prototype.bark(); } is some serious WTF. Because this.bark will already evaluate to the prototype method making this unnecessary. And calling it like this actually destroys the natural this value, as mentioned in #2.

Here is what is should be:

function Dog() {
  this.makeSound();
};

Dog.prototype.bark = function() {
  alert('woof');
};

Dog.prototype.makeSound = function() {
  this.bark();
};

Or alternatively, without the prototype at all:

function Dog() {
  this.bark = function() {
    alert('woof');
  };

  this.makeSound = function() {
    this.bark();
  };

  this.makeSound();
};

I would not trust this snippet of yours at all.

Leave a Comment