【问题标题】:How to make Constructor function to point to Super function prototype in ES5ES5中如何让构造函数指向超级函数原型
【发布时间】: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


    【解决方案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

    【讨论】:

      【解决方案2】:

      您希望 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-10
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 2010-12-06
        • 1970-01-01
        相关资源
        最近更新 更多