I am trying to understand why and when we use constructors in Javascript. I was wondering when and how we need to use the constructor of a child and when the parents. Based on my tests there is NO difference when I set the child constructor to itself or to the parent.Lets take a look at the below code :
function Mammal(name) {
this.name = "###"+name;
}
Cat.prototype = new Mammal(); // Here's where the inheritance occurs
Cat.prototype.constructor = Cat; // Otherwise instances of Cat would have a
function Cat(name) {
this.name = name;
}
Now lets instantiate the Cat and Mamal class and see the name:
var mycat = new Cat('Felix');
Alert(mycat.name); //OUTPUT : "Felix"
Now i want to set the constructor of Cat class to the Mamal. To do so I remove the below line
//Cat.prototype.constructor = Cat; -->Now the cat Constructor is set to its default(Mamal)
Now I expect that when I call mycat.name, it uses the Mamal constructor and alert "###Felix" BUT it doesn't. It shows exactly same as the previous result "Felix".
var mycat = new Cat('Felix');
Alert(mycat.name); //Again OUTPUT is : "Felix" !! but I expected "###Felix"
So, why? And can you give me an example of a correct use of constructors in Javascript and when they are important?