javascript - DataView 和原型(prototype)继承

标签 javascript prototype

根据我在网上看到的,在 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/

相关文章:

c++ - 为什么这个参数顺序在 regex_match 的原型(prototype)中?

javascript - 在 Angular/ionic4 中的自定义组件中传递参数?

javascript - 第7章, Eloquent JavaScript : LifelikeWorld

javascript - 使用 for 循环定位数组的元素而不是其位置时遇到问题

javascript - 使用 KineticJS 提高动画性能

JavaScript 原型(prototype)示例

javascript - 扩展对象字面量

"subclass"中的 Javascript 构造函数,正确的表示法?

javascript - 如何在 javascript 中获取用户输入并在页面上显示此输入?

javascript - 检测数组中接近且具有相同索引值的数字?