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:
function Packet(opcode, size) {
DataView.call(this, new ArrayBuffer(size));
setInt8(0, opcode);
}
Packet.prototype = Object.create(DataView.prototype);
Packet.prototype.send = function(websocket) {
websocket.send(this.buffer);
console.log('Packet sent!');
}
var ws = new WebSocket("ws://localhost:1337");
ws.onopen = function() {
var packet = new Packet(0, 5);
packet.setInt32(1337);
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'(…)
source
share