admin管理员组文章数量:1404923
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
本文标签: How to clone a constructor in JavaScriptStack Overflow
版权声明:本文标题:How to clone a constructor in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744877050a2629977.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论