如何在JavaScript中克隆构造函数?

时间:2013-01-14 03:20:35

标签: javascript

我有一个构造函数Monkey()

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

我想创建另一个名为Human()的构造函数,其中包含一个额外的属性cars,该属性将存储该人拥有的汽车数量以及Monkey具有的所有属性(如nameage

我不想重复新Monkey内容中的所有Human内容。是否可以克隆Monkey并使用 prototype 扩展属性?

3 个答案:

答案 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所述

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

答案 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));

另见