SharedArrayBuffer() 构造函数

注意:除非满足某些 安全要求,否则 SharedArrayBuffer 构造函数可能并不总是全局可用。

¥Note: The SharedArrayBuffer constructor may not always be globally available unless certain security requirements are met.

SharedArrayBuffer() 构造函数创建 SharedArrayBuffer 对象。

¥The SharedArrayBuffer() constructor creates SharedArrayBuffer objects.

Try it

语法

¥Syntax

js
new SharedArrayBuffer(length)
new SharedArrayBuffer(length, options)

注意:SharedArrayBuffer() 只能与 new 一起构建。尝试在没有 new 的情况下调用它会抛出 TypeError

¥Note: SharedArrayBuffer() can only be constructed with new. Attempting to call it without new throws a TypeError.

参数

¥Parameters

length

要创建的数组缓冲区的大小(以字节为单位)。

options Optional

一个对象,可以包含以下属性:

maxByteLength Optional

共享数组缓冲区可调整大小的最大大小(以字节为单位)。

返回值

¥Return value

指定大小的新 SharedArrayBuffer 对象,其 maxByteLength 属性设置为指定的 maxByteLength(如果已指定)。其内容初始化为 0。

¥A new SharedArrayBuffer object of the specified size, with its maxByteLength property set to the specified maxByteLength if one was specified. Its contents are initialized to 0.

示例

¥Examples

始终使用 new 运算符创建 SharedArrayBuffer

¥Always use the new operator to create a SharedArrayBuffer

SharedArrayBuffer 构造函数需要使用 new 运算符来构造。在没有 new 的情况下将 SharedArrayBuffer 构造函数作为函数调用将抛出 TypeError

¥SharedArrayBuffer constructors are required to be constructed with a new operator. Calling a SharedArrayBuffer constructor as a function without new will throw a TypeError.

js
const sab = SharedArrayBuffer(1024);
// TypeError: calling a builtin SharedArrayBuffer constructor
// without new is forbidden
js
const sab = new SharedArrayBuffer(1024);

增长可增长的 SharedArrayBuffer

¥Growing a growable SharedArrayBuffer

在此示例中,我们创建一个 8 字节缓冲区,最大长度可增长到 16 字节,然后将其 grow() 到 12 字节:

¥In this example, we create an 8-byte buffer that is growable to a max length of 16 bytes, then grow() it to 12 bytes:

js
const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 });

buffer.grow(12);

注意:建议将 maxByteLength 设置为适合你的用例的最小值。它不应超过 1073741824 (1GB),以降低内存不足错误的风险。

¥Note: It is recommended that maxByteLength is set to the smallest value possible for your use case. It should never exceed 1073741824 (1GB), to reduce the risk of out-of-memory errors.

规范

Specification
ECMAScript Language Specification
# sec-sharedarraybuffer-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看