Santosh Kumar
Santosh Kumar

Reputation: 27875

How to clone a constructor in JavaScript?

I have a constructor Monkey():

function Monkey(name, age) {
    this.name = name;
    this.age = age;
}

I want to make another constructor named Human() with an extra property cars which will store number of cars the person has along with all the property that Monkey has (like name and age)

I don't want to repeat all the Monkey stuff in the new Human stuff. Is is possible to clone the Monkey and extend a property with prototype?

Upvotes: 4

Views: 2450

Answers (3)

Danilo Valente
Danilo Valente

Reputation: 11352

I've tried this code, I guess it's what you want:

function Human(name,age,cars){
    Monkey.call(this,name,age);
    this.cars = cars;
}

This way, the Human constructor calls the Monkey constructor as a normal function, but setting its namespace as the new Human object. Thus, in this case, the this keyword inside Monkey constructor refers to a object of class Human, and not Monkey. Also, with this code, the condition new Human() instanceof Human; returns true, since I'm not returning a new instance of Monkey, just using its constructor.

Also, you can "clone" the prototype, as you said. Just do this:

Human.prototype = Monkey.prototype;

EDIT

As @Bergi amd suggested, the best way to clone a prototype is using the Object.create method, as follows:

Human.prototype = Object.create(Monkey.prototype, {constructor:{value:Human}});

Upvotes: 7

Matt Whipple
Matt Whipple

Reputation: 7134

Simple start for functional style/parasitic'ish inheritance:

function Human(name, age, cars) {
  var that = new Monkey(name, age);
  that.cars = cars;
  return that;
}

As outlined by Douglas Crockford

http://www.crockford.com/javascript/inheritance.html

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173582

I'm writing this answer simply to complement the others, it SHOULD NOT be used unless you fully know the impact of using the non-standard __proto__.

function Monkey(name, age) {
    this.name = name;
    this.age = age;
}

function Human(name, age, cars) {
  this.__proto__ = new Monkey(name, age);
  this.cars = cars;
}

console.log(new Human(1, 2, 3));

See also

Upvotes: 0

Related Questions