2

How does this syntax Penguin.prototype = new Animal(); inherit properties from constructor Animal. It also uses the "new" keyword, why does it use that? as far as I know, it is used to create objects.

Things that I know -There is actually no "class" in JavaScript. Every constructor/class or object has a prototype. We use "prototype" keyword to add properties or methods to it. We also use it to inherit properties from constructors, like in the above code. We can add methods or properties to object using dot operator, but we can't do that with constructors.

function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};


var Penguin = function(name) {
    this.name = name;
    this.numLegs = 2;
}    


Penguin.prototype = new Animal("lavios",89);
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Lavios
  • 1,169
  • 10
  • 22
  • Penguin.prototype is a new instance of the Animal constructor. – pro Jul 30 '15 at 23:39
  • Why are you confused? What about `Penguin.prototype = new Animal();` makes you think it shouldn't work? – Anonymous Jul 30 '15 at 23:43
  • 1
    You might [*MDN—Inheritance and the prototype chain*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) helpful. – RobG Jul 31 '15 at 00:26
  • possible duplicate of [What is the 'new' keyword in JavaScript?](http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) – Madness Jul 31 '15 at 03:45

0 Answers0