3

I have a function that is similar to each other. How can I make declaring a function easier without duplicating

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();
4
  • I don't see the problem with your code? Commented Jul 28, 2015 at 6:34
  • Yes that code is working. But what I want is to see improve coding techniques. As you can see my animal and penguin function constructor is almost the same. I want penguin to just inherit all the behaviour of Animal with less code. Commented Jul 28, 2015 at 6:37
  • 1
    Ah you want Penguin to inherit from Animal Commented Jul 28, 2015 at 6:37
  • Yes. I want to make my code dry. Commented Jul 28, 2015 at 6:42

1 Answer 1

8

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;
Sign up to request clarification or add additional context in comments.

3 Comments

is Penguin.prototype = Object.create(Animal.prototype); Penguin.prototype.constructor = Penguin; same as Penguin.prototype = new Animal();?
@thinker not really. a) Object.create is meant to create an object from an specific prototype, its no constructor... b) You need to have parameters to correctly call the constructor of Animal( ). c) What if the constructor of Animal enforces to have a name and a number of legs? It may throw an exception if no parameters provided. Object.create won't. d) You already called the constructor of Animal when you did Animal.call( ) so why would you want to call it again...
@thinker: No, ...prototype = new Animal(); is a sadly-common anti-pattern. More here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.