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
语法
参数
¥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.
示例
始终使用 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
.
const sab = SharedArrayBuffer(1024);
// TypeError: calling a builtin SharedArrayBuffer constructor
// without new is forbidden
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:
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 exceed1073741824
(1GB), to reduce the risk of out-of-memory errors.
规范
Specification |
---|
ECMAScript Language Specification # sec-sharedarraybuffer-constructor |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also