我有一个构造函数Monkey()
:
function Monkey(name, age) {
this.name = name;
this.age = age;
}
我想创建另一个名为Human()
的构造函数,其中包含一个额外的属性cars
,该属性将存储该人拥有的汽车数量以及Monkey
具有的所有属性(如name
和age
)
我不想重复新Monkey
内容中的所有Human
内容。是否可以克隆Monkey
并使用 prototype 扩展属性?
答案 0 :(得分:6)
我已经尝试过这段代码,我想这就是你想要的:
function Human(name,age,cars){
Monkey.call(this,name,age);
this.cars = cars;
}
这样,Human
构造函数将Monkey
构造函数作为普通函数调用,但将其命名空间设置为新的Human
对象。因此,在这种情况下,this
构造函数中的Monkey
关键字引用类Human
的对象,而不是Monkey.
此外,使用此代码,条件{{1返回new Human() instanceof Human;
,因为我没有返回true
的新实例,只是使用它的构造函数。
另外,正如你所说,你可以“克隆”原型。就这样做:
Monkey
修改强>
正如@Bergi amd建议的那样,克隆原型的最佳方法是使用Object.create method,如下所示:
Human.prototype = Monkey.prototype;
答案 1 :(得分:1)
功能样式/寄生'继承的简单开始:
function Human(name, age, cars) {
var that = new Monkey(name, age);
that.cars = cars;
return that;
}
如Douglas Crockford所述
答案 2 :(得分:0)
我写这个答案只是为了补充其他答案,除非你完全了解使用非标准__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));
另见