DataView 和原型继承 [英] DataView and prototypical Inheritance
问题描述
根据我在网上看到的,在 JavaScript 中扩展对象的一种方法是首先克隆它的原型,然后将该原型设置为子类的原型.
From what I've gleamed online, one way to extend an object in JavaScript is by first cloning it's prototype, then setting that prototype as the prototype of the subclass.
它似乎在这里不起作用:
It doesn't appear to be working here though:
// 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"类.
Here I am attempting to extend DataView in order to create a binary "Packet" class backed internally by an ArrayBuffer.
不幸的是,当我尝试创建此类的实例时,JavaScript 抛出此错误:
Unfortunately when I try to create an instance of this class, JavaScript throws this error:
Uncaught TypeError: Constructor DataView requires 'new'(…)
推荐答案
并非所有构造函数都允许您调用它们,例如ES6 类:
Not all constructors allow you to call them, e.g. ES6 classes:
class Foo {}
new Foo(); // OK
Foo(); // error
Foo.call(); // error
但是,DataView
可以使用 extends
语法进行子类化:
However, DataView
can be subclassed using the extends
syntax:
DataView
构造函数被设计为可子类化.它可能是用作类定义的 extends
子句的值.打算继承指定 DataView
的子类构造函数行为必须包括对 DataView
构造函数的 super
调用以使用内部状态创建和初始化子类实例必须支持 DataView.prototype
内置方法.
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);
这篇关于DataView 和原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!