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?
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?
3 Answers
Reset to default 7I'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}});
I'm writing this answer simply to plement 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
- __proto__, when will it be gone? Alternatives?
- JavaScript and __proto__ - what browsers use it?
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./javascript/inheritance.html