根据我在网上看到的,在 JavaScript 中扩展对象的一种方法是首先克隆它的原型(prototype),然后将该原型(prototype)设置为子类的原型(prototype)。
它似乎并没有在这里工作:
// 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);
}
在这里,我试图扩展 DataView 以创建一个由 ArrayBuffer 内部支持的二进制“Packet”类。
不幸的是,当我尝试创建此类的实例时,JavaScript 抛出此错误:
Uncaught TypeError: Constructor DataView requires 'new'(…)
最佳答案
不是所有的构造函数都允许你调用它们,例如ES6 类:
class Foo {}
new Foo(); // OK
Foo(); // error
Foo.call(); // error
然而,DataView
可以使用 extends
语法进行子类化:
The
DataView
constructor is designed to be subclassable. It may be used as the value of anextends
clause of a class definition. Subclass constructors that intend to inherit the specifiedDataView
behaviour must include asuper
call to theDataView
constructor to create and initialize subclass instances with the internal state necessary to support theDataView.prototype
built-in methods.
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);
关于javascript - DataView 和原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068518/