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

Javascript: how to append to a constructor's prototype, if that constructor is already defined on another object's prototype

本文关键字:构造函数 原型 定义 一个对象 何附加 如果 Javascript      更新时间:2023-09-26

如果我希望 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?

为什么不创建新的函数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' ]