简体   繁体   English

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

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

If I wanted an API to allow for aggregation-like inheritance using closures and the module pattern, I've come up with something like this: 如果我想要一个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' ]

This provides the API that I want when dealing with creating sub objects. 这提供了在创建子对象时所需的API。 However this line: 但是这一行:

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

seems like it should be written differently. 似乎应该用不同的方式写。 Ideally I would want to be able to append to the sub-constructor's prototype without specifying the entire prototype chain. 理想情况下,我希望能够在不指定整个原型链的情况下追加到子构造函数的原型。

Also, are there any better ways to achieve the same API? 另外,有没有更好的方法来实现相同的API?

why not creating new function Car 为什么不创建新功能的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' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM