DataView and prototype inheritance

From the fact that I shone on the Internet, one way to extend an object in JavaScript is to first clone its prototype and then set this prototype as a prototype of a subclass.

It doesn't seem to work here:

// Create constructor ...
function Packet(opcode, size) {
  DataView.call(this, new ArrayBuffer(size));
  setInt8(0, opcode);
}

// Extend DataView ...
Packet.prototype = Object.create(DataView.prototype);

// Create class method ...
Packet.prototype.send = function(websocket) {
  // Send packet here ...
  websocket.send(this.buffer);
  console.log('Packet sent!');
}

var ws = new WebSocket("ws://localhost:1337");

ws.onopen = function() {
  var packet = new Packet(0, 5);

  // Create packet here ...
  packet.setInt32(1337);

  // Send packet over ws ...
  packet.send(ws);
}

Here I am trying to extend the DataView to create the binary package class supported inside ArrayBuffer.

Unfortunately, when I try to instantiate this class, JavaScript throws this error:

Uncaught TypeError: Constructor DataView requires 'new'(…) 
+4
source share
1 answer

Not all constructors allow you to name them, for example. ES6 classes:

class Foo {}
new Foo(); // OK
Foo(); // error
Foo.call(); // error

However, DataViewyou can subclass using the syntax extends:

DataView . extends . , DataView super DataView DataView.prototype.

class Packet extends DataView {
  constructor(opcode, size) {
    super(new ArrayBuffer(size));
    this.setInt8(0, opcode);
  }
  send (websocket) {
    // Send packet here ...
  }
}
var packet = new Packet(0, 5);
+2

All Articles