gpt4 book ai didi

javascript - 如何从 Float32Array 创建矢量原型(prototype)?

转载 作者:行者123 更新时间:2023-12-02 18:56:01 25 4
gpt4 key购买 nike

var vector = function(x, y, z) {
this[0] = x || 0;
this[1] = y || 0;
this[2] = z || 0;
};

vector.prototype = new Float32Array(3);

vector.prototype.getLength = function() {
return Math.sqrt(Math.pow(this[0],2)+Math.pow(this[1],2)+Math.pow(this[2],2));
};

该向量是一个包含 3 个元素的 float32 数组。我不知道为什么它不起作用。如果我运行此代码,则会收到错误:'vec3.length' is not a function

var vec3 = new vector(3,4,5);
alert(vec3.getLength());
<小时/>

编辑:我用 getLength 替换了 length。现在它可以在除 Firefox 之外的任何地方运行。

最佳答案

Float32Arraylength 属性是只读,因此您无法将其替换为函数。在当前的规范草案中,您可以在 Section 7 中看到这一点。 :

interface TypedArray {
const unsigned long BYTES_PER_ELEMENT = element size in bytes;

readonly attribute unsigned long length; // <=== Note `readonly`

getter type get(unsigned long index);
setter void set(unsigned long index, type value);
void set(TypedArray array, optional unsigned long offset);
void set(type[] array, optional unsigned long offset);
TypedArray subarray(long begin, optional long end);
};
<小时/>

截至您的编辑:

I replaced length with getLength. Now it works everywhere except in firefox: (intermediate value).getLength is not a function

像这样交换问题的内容不太酷。但 Firefox 可能会认为 Float32Array 对象是不可扩展的。如果是这样,您可能需要添加另一层,以便可以将 getLength 放在中间原型(prototype)上。例如:

function protovector() {
}
protovector.prototype = new Float32Array(3);

function vector(/* ... */) {
}
vector.prototype = new protovector();
vector.prototype.getLength = function() {
// ...
};

或者只是将 lengthgetLength 放在实例上:

function vector(/* ... *) {
// this[0] = ...
this.length = function() {
// ...
};
}

但是由于类型化数组在构造时设置了固定长度,因此我不确定您首先使用 Float32Array 作为原型(prototype)能得到多少好处。

关于javascript - 如何从 Float32Array 创建矢量原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349557/

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