WebAssembly.Global
WebAssembly.Global
对象表示一个全局变量实例,可以被JavaScript 和importable/exportable 访问,跨越一个或多个WebAssembly.Module
实例.他允许被多个modules动态连接.
构造函数语法
var myGlobal = new WebAssembly.Global(descriptor, value);
参数
- descriptor
GlobalDescriptor
包含2个属性的表:value
: AUSVString
表示全局变量的数据类型.可以是i32
,i64
,f32
,或f64
.mutable
:布尔值决定是否可以修改.默认是false
.
- value
- 可以是任意变量值. This can be any value,需要其类型与变量类型匹配.如果变量没有定义,使用0代替,参考
DefaultValue
algorithm.
Global 构造函数属性
None.
Global 实例
所有的Global
实例继承自Global()
构造函数 prototype object —修改会影响所有Global
实例.
实例属性
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.
实例方法
Global.prototype.valueOf()
- Old-style method that returns the value contained inside the global variable.
例子
以下例子展示了使用WebAssembly.Global()
构造函数创建一个新的实例.它定义为可修饰的类型为i32
, 值为 0.
global的值发生改变,首先设置Global.value
为42,然后使用导出函数incGlobal()
增加为43.导出函数在global.wasm
模块中(它将参数的值加一并返回).
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); });
注意:你可以在running live on GitHub 查看例子;也可以访问source code.