1

In the following code , what's the benefit of having a constructor for Cat?

function Mammal(){
}
Mammal.prototype.breathe = function(){
    // do some breathing
};
function Cat(){
}
Cat.prototype = new Mammal();
Cat.prototype.constructor = Cat;
var garfield = new Cat();
console.log(garfield instanceof Cat);

With or without the constructor, it always prints true, as the result of checking instanceof.

In general do we have to bother setting the constructor?

Arian
  • 7,397
  • 21
  • 89
  • 177
  • when you overwrite the prototype of a function in JS you overwrite the constructor property as well. so you have to write back the constructor to it. so that when you create an object of `Cat` the constructor of cat would be called. – Minato Oct 14 '15 at 07:58
  • @MubashirHanif : But if I remove that line , it still works. why ? – Arian Oct 14 '15 at 08:07
  • http://stackoverflow.com/questions/4012998/what-it-the-significance-of-the-javascript-constructor-property – Matt Way Oct 14 '15 at 08:18

1 Answers1

3

In previous versions of ECMAScript, instanceof used the constructors in the object's prototype chain. In ES6, however, there is a Symbol that determines if an object is an instanceof a constructor, and that's more reliable since it takes a very delibarate effort to screw that Symbol.

However, an object's constructor can be useful in some cases where you want to create another object of the same type, e.g. for properly cloning an instance:

function clone(o) {
    var newO = new o.constructor()
    // copy properties
    return newO
}
Touffy
  • 6,309
  • 22
  • 28
  • thanks for the answer. btw isn't it better to use : `Cat.prototype = Object.create(Mammal.prototype)` rather than `Cat.prototype = new Mammal()` ? – Arian Oct 14 '15 at 08:26
  • 1
    Yes, it is. And my `clone()` function could also use that. None of that is relevant to your question, but it's absolutely right. – Touffy Oct 14 '15 at 08:30