Search code examples
javascriptinheritanceprototype

Js inherit from class via prototypes


I need to inherit DataView object to create my own type and add additional methods etc. But I'm a bit confused how to do this in a right way. I tried to do like this:

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;
   }
};

But got an error:

DataView.prototype.byteLength called on incompatible receiver CFDataView

From the proposals, I tried to do like this:

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;

But receive an error:

TypeError: Constructor DataView requires 'new'


Solution

  • You need to use ES6 class to extend the native classes such as DataView. As the error messages say, you can only use the methods on real dataviews ("compatible receivers"), and to create such you need to use the DataView constructor (with new - or with super or Reflect.construct). So

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