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

标签 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');
};

好像应该写成不同的。理想情况下,我希望能够附加到子构造函数的原型(prototype)而不指定整个原型(prototype)链。

另外,有没有更好的方法来实现相同的 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' ]

关于Javascript:如果该构造函数已在另一个对象的原型(prototype)上定义,如何附加到构造函数的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969867/

相关文章:

javascript - 大括号在变量声明中是什么意思?

javascript - jquery - .hash 在此函数中的意义

javascript - Suitescript从多个选择字段加载项目记录

javascript - 将隐藏的输入值获取到jquery变量

javascript - Highcharts - 甘特图绘图问题

javascript - 了解 Backbone.js REST 调用

javascript - 增加变量名

javascript - 检测子 div 是否比父 div 宽?

javascript - 使用页面子元素测量页面下载时间和渲染时间

javascript - 术语执行上下文和范围之间有区别吗?