Javascript 如何在ES5中使构造函数指向超级函数原型
我的问题标题可能看起来完全令人困惑,这反映了我目前的心态:p 我正在重新访问JavaScript继承世界的基础知识。下面的例子应该说明我想做什么:Javascript 如何在ES5中使构造函数指向超级函数原型,javascript,jquery,javascript-objects,ecmascript-5,Javascript,Jquery,Javascript Objects,Ecmascript 5,我的问题标题可能看起来完全令人困惑,这反映了我目前的心态:p 我正在重新访问JavaScript继承世界的基础知识。下面的例子应该说明我想做什么: function Vehicle(engType, wheels, color){ this._engType = engType; this._wheels = wheels; this._color = color; } var VP = Vehicle.prototype; VP.setEngType = funct
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();
车辆是具有自身属性集的超级类型,而车辆是具有自身属性集的子类型
在这里之前一切都很好,但一旦我创建了Car实例并想设置其父对象的其他属性,比如engType
/wheels
/color
,我需要使用set accessor方法,这是一项开销。在Car(子类型)构造函数中是否有立即执行此操作的方法。比如:
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);
}
你可以这样打电话
function Car(cc, gears, engType, wheels, color){
Vehicle.call(this,engType,wheels,color);
this._cc = cc;
this._gears = gears;
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
有关更多详细信息,请参阅此您可以这样调用
function Car(cc, gears, engType, wheels, color){
Vehicle.call(this,engType,wheels,color);
this._cc = cc;
this._gears = gears;
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
有关更多详细信息,请参阅此您希望新实例上的父构造函数(此
)进行初始化:
function Car(cc, gears, engType, wheels, color) {
Vehicle.call(this, engType, wheels, color);
this._cc = cc;
this._gears = gears;
}
并创建原型:
Car.prototype = Object.create(VP);
您希望在新实例(this
)上使用父构造函数进行初始化:
function Car(cc, gears, engType, wheels, color) {
Vehicle.call(this, engType, wheels, color);
this._cc = cc;
this._gears = gears;
}
并创建原型:
Car.prototype = Object.create(VP);