--- title: WebAssembly.instantiate() slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate ---
WebAssembly.instantiate()
允许你编译和实例化 WebAssembly 代码。这个方法有两个重载方式:
Promise
会携带已编译的 {{jsxref("WebAssembly.Module")}} 和它的第一个实例化对象 {{jsxref("WebAssembly.Instance")}}.Promise
携带一个 Module
的实例化对象 Instance
. 如果这个 Module
已经被编译了或者是从缓存中获取的( retrieved from cache), 那么这种重载方式是非常有用的.警告:此方法不是获取(fetch)和实例化wasm模块的最具效率方法。 如果可能的话,您应该改用较新的{{jsxref("WebAssembly.instantiateStreaming()")}}方法,该方法直接从原始字节码中直接获取,编译和实例化模块,因此不需要转换为{{jsxref("ArrayBuffer")}}。
Promise<ResultObject> WebAssembly.instantiate(bufferSource, importObject);
解析为包含两个字段的 ResultObject
的一个 Promise
:
module
: 一个被编译好的 {{jsxref("WebAssembly.Module")}} 对象. 这个模块可以被再次实例化,通过 postMessage() 被分享,或者缓存到 IndexedDB。instance
: 一个包含所有 Exported WebAssembly functions的{{jsxref("WebAssembly.Instance")}}对象。Promise<WebAssembly.Instance> WebAssembly.instantiate(module, importObject);
一个解析为 {{jsxref("WebAssembly.Instance")}} 的Promise
对象。
提示: 在大多数情况下,您可能需要使用{{jsxref("WebAssembly.instantiateStreaming()")}},因为它比instantiate()
更具效率。
使用 fetch 获取一些 WebAssembly 二进制代码后,我们使用 {{jsxref("WebAssembly.instantiate()")}} 方法编译并实例化模块,在此过程中,导入了一个 Javascript 方法在 WebAssembly 模块中, 接下来我们使用Instance
导出的Exported WebAssembly 方法。
var importObject = { imports: { imported_func: function(arg) { console.log(arg); } }, env: { abort: () => {}, }, }; /* 2019-08-03:importObject必须存在env对象以及env对象的abort方法 */ fetch('simple.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(result => result.instance.exports );
备注:: 查看GitHub(在线实例)的 index.html 中一个相似的例子,使用了我们的fetchAndInstantiate()
库函数
下面的例子(查看我们GitHub的 index-compile.html 例子,可在线演示)使用 compile()
方法编译了 simple.wasm 字节码,然后通过 postMessage() 发送给一个线程 worker。
var worker = new Worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.compile(bytes) ).then(mod => worker.postMessage(mod) );
在线程中 (查看 wasm_worker.js
) 我们定义了一个导入对象供模块使用,然后设置了一个事件处理函数来接收主线程发来的模块。当模块被接收到后,我们使用{{jsxref("WebAssembly.instantiate()")}} 方法创建一个实例并且调用它从内部导出的函数。
var importObject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; WebAssembly.instantiate(mod, importObject).then(function(instance) { instance.exports.exported_func(); }); };
Specification | Status | Comment |
---|---|---|
{{SpecName('WebAssembly JS', '#webassemblyinstantiate', 'instantiate()')}} | {{Spec2('WebAssembly JS')}} | Initial draft definition. |