gpt4 book ai didi

javascript - DataView 和原型(prototype)继承

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:20 26 4
gpt4 key购买 nike

根据我在网上看到的,在 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 an extends clause of a class definition. Subclass constructors that intend to inherit the specified DataView behaviour must include a super call to the DataView constructor to create and initialize subclass instances with the internal state necessary to support the DataView.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com