--- title: WebAssembly.instantiate() slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate ---
{{JSRef}}

WebAssembly.instantiate() 允许你编译和实例化 WebAssembly 代码。这个方法有两个重载方式:

警告:此方法不是获取(fetch)和实例化wasm模块的最具效率方法。 如果可能的话,您应该改用较新的{{jsxref("WebAssembly.instantiateStreaming()")}}方法,该方法直接从原始字节码中直接获取,编译和实例化模块,因此不需要转换为{{jsxref("ArrayBuffer")}}。

语法

主重载方式 — 使用wasm二进制代码

Promise<ResultObject> WebAssembly.instantiate(bufferSource, importObject);

参数

bufferSource
一个包含你想编译的wasm模块二进制代码的 typed array(类型数组) or ArrayBuffer(数组缓冲区)
importObject {{optional_inline}}
一个将被导入到新创建实例中的对象,它包含的值有函数、{{jsxref("WebAssembly.Memory")}} 对象等等。编译的模块中,对于每一个导入的值都要有一个与其匹配的属性与之相对应,否则将会抛出 WebAssembly.LinkError

返回值

解析为包含两个字段的 ResultObject 的一个 Promise:

异常

第二种重载 — 使用模块对象

Promise<WebAssembly.Instance> WebAssembly.instantiate(module, importObject);

参数

module
将被实例化的 {{jsxref("WebAssembly.Module")}} 对象。
importObject {{optional_inline}}
一个将被导入到新创建实例中的对象,它包含的值有函数、{{jsxref("WebAssembly.Memory")}} 对象等等。编译的模块中,对于每一个导入的值都要有一个与其匹配的属性与之相对应,否则将会抛出{{jsxref("WebAssembly.LinkError")}} 。

返回值

一个解析为 {{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.

浏览器兼容性

{{Compat}}

参见