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