0

In this answer on a question about inheritance in JavaScript, Oriol adds the line

Cat.prototype.constructor = Cat;

What is this for?

Could you give me an example of one (or some) bad things that could happen if this were omitted and the inheritance was simply:

function Animal(name, sound) {
  this.name = name;
  this.sound = sound;
}

function Cat(name) {
  Animal.call(this, name, 'Meow');
}

Cat.prototype = Object.create(Animal.prototype);
Community
  • 1
  • 1
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • [**Object.prototype.constructor**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) – adeneo Dec 01 '14 at 18:19
  • @adeneo, Thanks, but that tells me what it is, but not why it is or why it's important. – BanksySan Dec 01 '14 at 18:25
  • 1
    The `constructor` property is mostly just FYI and by default holds a reference to the `function` it was defined for. The property isn't used by JavaScript itself, though it could be used by some libraries or tools. The assignment of `Cat` as the `constructor` just restores the value it held before the whole `prototype` was replaced -- http://jsfiddle.net/u3p9gghv/. – Jonathan Lonowski Dec 01 '14 at 18:34

0 Answers0