Javascript:如果已经在另一个对象的原型上定义了该构造函数,如何附加到构造函数的原型

时间:2016-03-13 11:49:53

标签: javascript

如果我想要一个API允许使用闭包和模块模式进行类似聚合的继承,我会想出这样的东西:

function Vehicle(category) {
    this.category = category;
    return {
        Car: this.Car
    };
};

Vehicle.prototype.Car = function(type) {
    this.wheels = [];
    this.type = type;
    return {
        type: this.type,
        wheels: this.wheels,
        addWheel: this.addWheel,
    };
};

Vehicle.prototype.Car.prototype.addWheel = function() {
    this.wheels.push('a wheel');
};

roadCars = new Vehicle('Road Cars');
roadCars.honda = new roadCars.Car('Honda');
roadCars.honda.addWheel();

console.log(roadCars.honda.wheels); // [ 'a wheel' ]

这提供了在处理创建子对象时我想要的API。不过这一行:

Vehicle.prototype.Car.prototype.addWheel = function() {
    this.wheels.push('a wheel');
};

似乎应该以不同的方式编写。理想情况下,我希望能够在不指定整个原型链的情况下附加到子构造函数的原型。

此外,有没有更好的方法来实现相同的API?

1 个答案:

答案 0 :(得分:1)

为什么不创建新功能Car

function Vehicle(category) {
    this.category = category;
    return {
        Car: this.Car
    };
};

function Car(type) {
    this.wheels = [];
    this.type = type;
    return {
        type: this.type,
        wheels: this.wheels,
        addWheel: this.addWheel,
    };
};

Car.prototype.addWheel = function() {
    this.wheels.push('a wheel');
};

Vehicle.prototype.Car = Car

roadCars = new Vehicle('Road Cars');
roadCars.honda = new roadCars.Car('Honda');
roadCars.honda.addWheel();

console.log(roadCars.honda.wheels); // [ 'a wheel' ]