Inherit function in javascript

I have a function that is similar to another. How can I simplify the function declaration without duplication

function constructor (name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
} 

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

 // create a Penguin constructor here
 function Penguin(name, numLegs){
     this.name=name;
     this.numLegs = numLegs;
 }

 // create a sayName method for Penguins here
 Penguin.prototype.sayName = function() {
     console.log("Hi my name is " + this.name);
 };

 // our test code
 var theCaptain = new Penguin("Captain Cook", 2);
 theCaptain.sayName();

      

+3


source to share


1 answer


You were almost there.



// create a Penguin constructor here
function Penguin(name, numLegs){
    Animal.call(this, name, numLegs);
};

// Reuse the prototype chain
Penguin.prototype = Object.create(Animal.prototype);
Penguin.prototype.constructor = Penguin;

      

+8


source







All Articles