Javascript:如何附加到构造函数的原型,如果该构造函数已经在另一个对象的原型上定义
Javascript: how to append to a constructor's prototype, if that constructor is already defined on another object's prototype
如果我希望 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' ]
相关文章:
- 如何从构造函数中调用js原型方法
- 通过原型/构造函数从复选框输出值
- Javascript:继承原型而不重新定义构造函数
- 使用sinon.js创建一个“;“间谍对象”;使用基于真实构造函数/原型的间谍方法
- 使用构造函数 - 原型从文本框输出值
- 在构造函数中定义函数会比将其附加到原型消耗更多的内存
- JS构造函数的原型属性与其原型之间的区别
- Javascript 中的构造函数不会返回由原型函数传递的正确值
- 构造函数原型-继承混淆
- 为什么我的代码认为 canvas 函数在 JavaScript 中的构造函数原型中是未定义的
- 我应该使用构造函数/原型吗?
- 对象文字与构造函数+原型
- 从画布构造函数原型中绘制图像
- 如何给构造函数/原型函数增加值?
- 构造函数.原型不在原型链中
- 向构造函数原型添加方法
- 为什么组合构造函数/原型模式返回对象类型
- 更改构造函数原型时出现问题
- 如何创建带有未分配属性的Javascript构造函数/原型
- 构造函数-原型- __proto__