为什么 Float32Array.length 的值总是 3?

Why is the value of Float32Array.length always 3?

我正在阅读 the Mozilla Developer Network docs on Float32Arrays 的时候看到了

Float32Array.length
Length property whose value is 3.

...为什么总是3?我还注意到同名的原型 属性 覆盖了它。

Float32Array其实就是一个函数。你可以这样检查

console.assert(typeof Float32Array === 'function');

并且该函数接受三个参数。引用同一文档中的签名,

Float32Array(buffer [, byteOffset [, length]]);

引用 Function.length documentation,

length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters.

这就是为什么 Float32Arraylength 属性 总是 3.

因为构造函数最多接受3个参数:

Float32Array(buffer [, byteOffset [, length]]);

JavaScript 中的每个函数都有一个长度 属性,这将 return 它采用的命名参数的计数。

例如

function foo(a, b) {}
foo.length === 2; // true

function bar() {}
bar.length === 0; // true

这是 (object-) 函数 Float32Array.

参数数量的长度

然而,当你实例化它时length将代表索引的数量:

console.log(Float32Array.length);  // => 3, number of arguments

var a = new Float32Array(10);      // create an instance with 10 indexes
console.log(a.length);             // => 10, number of indexes