Js通过原型继承自类

时间:2018-05-08 05:37:06

标签: javascript inheritance prototype

我需要继承DataView对象来创建我自己的type并添加其他方法等。但我有点困惑如何以正确的方式做到这一点。我试着这样做:

var CFDataView = function() {
    this.offset = 0;
};

CFDataView.prototype.__proto__ = DataView.prototype;

CFDataView.prototype.readU8 = function() {
   if (this.byteLength >= this.offset+1) {
     return this.getUint8(this.offset++);
   } else {
     return null;
   }
};

但得到了一个错误:

  

DataView.prototype.byteLength调用了不兼容的接收器CFDataView

从提案中,我试图这样做:

var CFDataView = function CFDataView(buffer, byteOffset, byteLength) {
            DataView.call(this, buffer, byteOffset, byteLength);
            this.offset = 0;
        };

        CFDataView.prototype = Object.create(DataView.prototype);
        CFDataView.prototype.constructor = CFDataView;

但收到错误:

  

TypeError:构造函数DataView需要“new”

1 个答案:

答案 0 :(得分:0)

您需要使用ES6 class来扩展本地类,例如DataView。正如错误消息所说,您只能在真实数据视图(“兼容接收器”)上使用这些方法,并且要创建这样的方法,您需要使用DataView构造函数(使用new - 或使用{{1 }或super)。所以

Reflect.construct
相关问题