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’ve tried this code, I guess it’s what you want:
This way, the
Humanconstructor calls theMonkeyconstructor as a normal function, but setting its namespace as the newHumanobject. Thus, in this case, thethiskeyword insideMonkeyconstructor refers to a object of classHuman, and notMonkey.Also, with this code, the conditionnew Human() instanceof Human;returnstrue, since I’m not returning a new instance ofMonkey, just using its constructor.Also, you can “clone” the prototype, as you said. Just do this:
EDIT
As @Bergi amd suggested, the best way to clone a prototype is using the Object.create method, as follows: