【问题标题】:Js inherit from class via prototypesJs 通过原型从类继承
【发布时间】:2018-05-08 05:37:05
【问题描述】:

我需要继承 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'

【问题讨论】:

    标签: javascript inheritance prototype


    【解决方案1】:

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

    class CFDataView {
      constructor(...args) {
        super(...args)
        this.offset = 0;
      }
      readU8() {
        if (this.byteLength >= this.offset+1) {
          return this.getUint8(this.offset++);
        } else {
          return null;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多