ES5中如何让构造函数指向超函数原型
How to make Constructor function to point to Super function prototype in ES5
我的问题标题可能看起来很混乱,这反映了我目前的心态:P
我是 re-visiting 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 super-type 有自己的一组属性,Car 有自己的 sub-type 的 Vehicle。
到这里为止一切都很好但是一旦我创建了 Car 的实例并想设置它的其他属性 parent 说 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);
}
你可以这样调用,
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;
更多详细信息,请参阅此website
您想 call
新实例 (this
) 的父构造函数进行初始化:
function Car(cc, gears, engType, wheels, color) {
Vehicle.call(this, engType, wheels, color);
this._cc = cc;
this._gears = gears;
}
并don't use a new
call创建原型:
Car.prototype = Object.create(VP);
我的问题标题可能看起来很混乱,这反映了我目前的心态:P
我是 re-visiting 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 super-type 有自己的一组属性,Car 有自己的 sub-type 的 Vehicle。
到这里为止一切都很好但是一旦我创建了 Car 的实例并想设置它的其他属性 parent 说 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);
}
你可以这样调用,
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;
更多详细信息,请参阅此website
您想 call
新实例 (this
) 的父构造函数进行初始化:
function Car(cc, gears, engType, wheels, color) {
Vehicle.call(this, engType, wheels, color);
this._cc = cc;
this._gears = gears;
}
并don't use a new
call创建原型:
Car.prototype = Object.create(VP);