我想创建一个名为 Matrix4
的类,它扩展了 Float32Array
。我希望能够使用创建 16 个元素数组的构造函数覆盖 Float32Array
构造函数(通常我会调用 new Float32Array(16)
,但现在我只想新 Matrix4
).
// This function should override the Float32Array constructor
// And create a Matrix4 object with the size of 16 elements
var Matrix4 = function() {
Float32Array.call(this, 16);
};
Matrix4.prototype = new Float32Array;
我从这段代码得到的错误是:
构造函数 Float32Array 需要 'new'
最佳答案
您不能使用老式的 ES6 之前的语法扩展内置对象,例如 Array
或 Float32Array
。唯一的方法是使用 a class..extends
statement :
class Matrix4 extends Float32Array {
constructor() {
super(16);
}
}
let matrix = new Matrix4;
console.log(matrix.length); // 16
关于javascript - 扩展 Array 类时如何覆盖构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896933/