如何使构造函数在ES5中指向超级函数原型

时间:2017-05-26 06:56:56

标签: 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 = 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有自己的属性,是车辆的子类型。

直到这里一切都很好但是一旦我创建了Car的实例并想要设置其父级的其他属性,请说engType / wheels / color我需要使用Set accessor方法是一个开销。有没有办法在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);
}

2 个答案:

答案 0 :(得分:1)

你可以这样打电话,

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

答案 1 :(得分:1)

您想要https://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html#basic-usage新实例(this)上的父构造函数进行初始化:

function Car(cc, gears, engType, wheels, color) {
    Vehicle.call(this, engType, wheels, color);
    this._cc = cc;
    this._gears = gears;
}

call创建原型:

Car.prototype = Object.create(VP);