如果我想要一个 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/