【发布时间】:2017-05-26 06:56:55
【问题描述】:
我的问题标题可能看起来完全混乱,这反映了我目前的心态:P
我正在重新访问 JavaScript 继承世界的基础知识。下面的例子应该告诉我想做什么:
function Vehicle(engType, wheels, color){
this._engType = engType;
this._wheels = wheels;
this._color = color;
}
var VP = Vehicle.prototype;
VP.setEngType = function(engType){
this._engType = engType;
}
VP.setWheels = function(wheels){
this._wheels = wheels;
}
VP.setColor = function(color){
this._color = color;
}
function Car(cc, gears){
this._cc = cc;
this._gears = gears;
}
Car.prototype = new Vehicle();
Vehicle 是具有自己的一组属性的超类型,而 Car 具有自己的属性,它是 Vehicle 的子类型。
到这里为止一切都很好,但是一旦我创建了 Car 的实例并想要设置其父级的其他属性说 engType / wheels / color 我需要使用 Set 访问器方法,这是一个开销。有没有办法在 Car (Sub-Type) 构造函数中立即执行此操作。喜欢:
function Car(cc, gears, engType, wheels, color){
this._cc = cc;
this._gears = gears;
// Setting super type props
this.setEngType(engType);
this.setWheels(wheels);
this.setColor(color);
}
【问题讨论】:
标签: javascript jquery javascript-objects ecmascript-5