--- title: WebAssembly.Global slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global tags: - API - Constructor - JavaScript - Reference - WebAssembly - global translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global ---
WebAssembly.Global はグローバル変数として存在し、JavaScript または {{jsxref("WebAssembly.Module")}} インスタンスから参照することができます。これにより動的に複数のモジュールをリンクすることができます。
var myGlobal = new WebAssembly.Global(descriptor, value);
GlobalDescriptor 辞書オブジェクト、2 つの要素を持っている:
value: {{domxref("USVString")}} はグローバルデータ形式を表し値として i32、i64、f32、f64 のうち一つを取ります。mutable: グローバルがミュータブルかどうかの真偽値です。デフォルトでは false です。DefaultValue algorithm で指定した時の様な 型ありの 0 が使われます。無し
すべてのグローバルインスタンスは Global() コンストラクターのプロパティオブジェクトを受け継ぐ — これによりすべての Global インスタンスを変更できる
{{page('/ja/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype', 'Properties')}}
{{page('/ja/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype', 'Methods')}}
以下の例では新しいグローバルインスタンスは WebAssembly.Global() コンストラクターを用いて初期化され、初期値 0 のミュータブルな i32 型として定義されます。
その後この値は、Global.value プロパティを使うことによって 42 に、global.wasm モジュールから公開された incGlobal() 関数 (入力に限らず 1 を加算する) を使うことによって 43 になります。
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);
});
メモ: GitHub 上で動くデモが試せます。ソースコードも確認してみてください。
| 仕様 | 策定状況 | コメント |
|---|---|---|
| {{SpecName('WebAssembly JS', '#globals', 'WebAssembly.Global()')}} | {{Spec2('WebAssembly JS')}} | 初回ドラフト定義 |
{{Compat("javascript.builtins.WebAssembly.Global")}}