WebAssembly.Global - JavaScript 编辑

A WebAssembly.Global object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This allows dynamic linking of multiple modules.

Constructor

WebAssembly.Global()
Creates a new Global object.

Global instances

All Global instances inherit from the Global() constructor's prototype object — this can be modified to affect all Global instances.

Instance properties

Global.prototype.constructor
Returns the function that created this object's instance. By default this is the WebAssembly.Global() constructor.
Global.prototype[@@toStringTag]
The initial value of the @@toStringTag property is the String value "WebAssembly.Global".
Global.prototype.value
The value contained inside the global variable — this can be used to directly set and get the global's value.

Instance methods

Global.prototype.valueOf()
Old-style method that returns the value contained inside the global variable.

Examples

Creating a new Global instance

The following example shows a new global instance being created using the WebAssembly.Global() constructor. It is being defined as a mutable i32 type, with a value of 0.

The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value).

const output = document.getElementById('output');

function assertEq(msg, got, expected) {
  output.innerHTML += `Testing ${msg}: `;
  if (got !== expected)
    output.innerHTML += `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
  else
    output.innerHTML += `SUCCESS! Got: ${got}<br>`;
}

assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");

const global = new WebAssembly.Global({value:'i32', mutable:true}, 0);

WebAssembly.instantiateStreaming(fetch('global.wasm'), { js: { global } })
.then(({instance}) => {
    assertEq("getting initial value from wasm", instance.exports.getGlobal(), 0);
    global.value = 42;
    assertEq("getting JS-updated value from wasm", instance.exports.getGlobal(), 42);
    instance.exports.incGlobal();
    assertEq("getting wasm-updated value from JS", global.value, 43);
});

Note: You can see the example running live on GitHub; see also the source code.

Specifications

Specification
WebAssembly JavaScript Interface
The definition of 'WebAssembly.Global()' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:190 次

字数:5362

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文