> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# JavaScript 运行时与 WebAssembly

## JavaScript 运行时

Lynx 最大的特点之一是[双线程架构](/next/zh/guide/spec.md#scripting-facing-threading-abstraction)（更多信息请参阅 [ReactLynx 编程思想](/next/zh/react/thinking-in-reactlynx.md)），JavaScript 代码会在[主线程](/next/zh/guide/spec.md#main-thread-or-lynx-main-thread)和[后台线程](/next/zh/guide/spec.md#background-thread-aka-off-main-thread)两个线程上同时运行。两个线程使用了不同的 JavaScript 引擎作为其运行时。

### [主线程](/next/zh/guide/spec.md#main-thread-or-lynx-main-thread)

Lynx 主线程负责处理直接影响屏幕[像素渲染](/next/zh/guide/spec.md#enginepixeling-the-pixel-pipeline)的任务，包括：执行[主线程脚本](/next/zh/react/main-thread-script.md)、处理布局和渲染图形等等。

主线程使用由 Lynx 团队官方维护的 [PrimJS](/next/zh/guide/scripting-runtime/main-thread-runtime.md#primjs) 作为运行时，它是基于 QuickJS 的轻量、高性能 JavaScript 引擎，可以为主线程提供良好的运行性能。

### [后台线程](/next/zh/guide/spec.md#background-thread-aka-off-main-thread)

相对于主线程，Lynx 的后台线程处理的任务不直接影响屏幕像素的显示。这包括在后台运行的脚本和任务，它们与主线程分开运行。这样可以让主线程专注于处理用户交互和渲染，从而提升整体性能。

- Android：出于包体积和性能的综合考量，我们默认使用 [PrimJS](/next/zh/guide/scripting-runtime/main-thread-runtime.md#primjs) 作为运行时
- iOS：默认情况下使用 [JavaScriptCore](https://trac.webkit.org/wiki/JavaScriptCore) 作为运行时，但由于调试协议支持度的原因，当需要调试的时候，需要切换到 [PrimJS](/next/zh/guide/scripting-runtime/main-thread-runtime.md#primjs)。

虽然这些运行时引擎环境非常相似，但最终可能会遇到一些不一致的地方，请避免依赖任何运行时的具体细节。

## WebAssembly

从 Lynx 3.8 开始，Lynx 基于 PrimJS 集成为 Android 提供了基础的 WebAssembly 支持。

这项能力面向常见的模块加载和执行场景，目前仅支持后台线程。目前 Lynx 并未暴露完整的 WebAssembly JavaScript API。支持范围和当前限制请参考 [WebAssembly](/next/zh/guide/scripting-runtime/webassembly.md)。

## JavaScript 语法转换

Lynx 双线程运行时支持最高的 ECMAScript 版本分别是：

- 主线程：[ECMAScript 2019 (ES10)](https://tc39.es/ecma262/2019/)
- 后台线程：[ECMAScript 2015 (ES6)](https://262.ecma-international.org/6.0/)

当然，你可以使用新版本的 JavaScript 语法来编写代码，在构建时会使用 [SWC](https://swc.rs/) 进行语法转换，而不需要等待 JavaScript 运行时支持。

## JavaScript Polyfills

:::info
仅在 iOS 系统中注入 Polyfills

完整的 polyfill 列表见[仓库](https://github.com/lynx-family/lynx/blob/develop/js_libraries/lynx-polyfill/src/index.js)
:::

除了对语法进行转换外，Lynx 还对很多内置的 API 提供了 polyfill，包括：

### Built-in Objects

- [Map](https://tc39.es/ecma262/#sec-map-constructor)
- [Set](https://tc39.es/ecma262/#sec-set-constructor)
- [WeakMap](https://tc39.es/ecma262/#sec-weakmap-constructor)
- [WeakSet](https://tc39.es/ecma262/#sec-weakset-constructor)

### Array

- [Array.prototype.concat](https://tc39.es/ecma262/#sec-array.prototype.concat)
- [Array.prototype.filter](https://tc39.es/ecma262/#sec-array.prototype.filter)
- [Array.prototype.flat](https://tc39.es/ecma262/#sec-array.prototype.flat)
- [Array.prototype.flatMap](https://tc39.es/ecma262/#sec-array.prototype.flatmap)
- [Array.prototype.includes](https://tc39.es/ecma262/#sec-array.prototype.includes)
- [Array.prototype\[@@iterator\]](https://tc39.es/ecma262/#sec-array.prototype-@@iterator)
- [Array.prototype.map](https://tc39.es/ecma262/#sec-array.prototype.map)
- [Array.prototype.reverse](https://tc39.es/ecma262/#sec-array.prototype.reverse)
- [Array.prototype.slice](https://tc39.es/ecma262/#sec-array.prototype.slice)
- [Array.prototype.sort](https://tc39.es/ecma262/#sec-array.prototype.sort)
- [Array.prototype.species](https://tc39.es/ecma262/#sec-array.prototype.species)
- [Array.prototype.splice](https://tc39.es/ecma262/#sec-array.prototype.splice)
- [Array.prototype\[@@unscopables\].flat](https://tc39.es/ecma262/#sec-array.prototype-@@unscopables)
- [Array.prototype\[@@unscopables\].flatMap](https://tc39.es/ecma262/#sec-array.prototype-@@unscopables)

### ArrayBuffer

- [ArrayBuffer](https://tc39.es/ecma262/#sec-arraybuffer-objects)
- [ArrayBuffer.prototype.slice](https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice)

### Date

- [Date.prototype.toJSON](https://tc39.es/ecma262/#sec-date.prototype.tojson)
- [Date.prototype\[@@toPrimitive\]](https://tc39.es/ecma262/#sec-date.prototype-@@toprimitive)

### Number

- [Number.parseFloat](https://tc39.es/ecma262/#sec-number.parseFloat)

### Object

- [Object.entries](https://tc39.es/ecma262/#sec-object.entries)
- [Object.fromEntries](https://tc39.es/ecma262/#sec-object.fromentries)
- [Object.getOwnPropertyDescriptors](https://tc39.es/ecma262/#sec-object.getownpropertydescriptors)
- [Object.toString](https://tc39.es/ecma262/#sec-object.tostring)
- [Object.values](https://tc39.es/ecma262/#sec-object.values)

### Promise

- [Promise](https://tc39.es/ecma262/#sec-promise-constructor)
- [Promise.all](https://tc39.es/ecma262/#sec-promise.all)
- [Promise.race](https://tc39.es/ecma262/#sec-promise.race)
- [Promise.reject](https://tc39.es/ecma262/#sec-promise.reject)
- [Promise.resolve](https://tc39.es/ecma262/#sec-promise.resolve)
- [Promise.prototype.catch](https://tc39.es/ecma262/#sec-promise.prototype.catch)
- [Promise.prototype.finally](https://tc39.es/ecma262/#sec-promise.prototype.finally)
- [Promise.prototype.then](https://tc39.es/ecma262/#sec-promise.prototype.then)

### Reflect

- [Reflect.apply](https://tc39.es/ecma262/#sec-reflect.apply)
- [Reflect.construct](https://tc39.es/ecma262/#sec-reflect.construct)
- [Reflect.defineProperty](https://tc39.es/ecma262/#sec-reflect.defineproperty)
- [Reflect.deleteProperty](https://tc39.es/ecma262/#sec-reflect.deleteproperty)
- [Reflect.get](https://tc39.es/ecma262/#sec-reflect.get)
- [Reflect.getOwnPropertyDescriptors](https://tc39.es/ecma262/#sec-reflect.getownpropertydescriptor)
- [Reflect.getPrototypeOf](https://tc39.es/ecma262/#sec-reflect.getprototypeof)
- [Reflect.has](https://tc39.es/ecma262/#sec-reflect.has)
- [Reflect.isExtensible](https://tc39.es/ecma262/#sec-reflect.isextensible)
- [Reflect.ownKeys](https://tc39.es/ecma262/#sec-reflect.ownkeys)
- [Reflect.preventExtensions](https://tc39.es/ecma262/#sec-reflect.preventextensions)
- [Reflect.set](https://tc39.es/ecma262/#sec-reflect.set)
- [Reflect.setPrototypeOf](https://tc39.es/ecma262/#sec-reflect.setprototypeof)

### RegExp

- [RegExp](https://tc39.es/ecma262/#sec-regexp-constructor)
- [RegExp.prototype.exec](https://tc39.es/ecma262/#sec-regexp.prototype.exec)
- [RegExp.prototype.sticky](https://tc39.es/ecma262/#sec-regexp.prototype.sticky)
- [RegExp.prototype.test](https://tc39.es/ecma262/#sec-regexp.prototype.test)
- [RegExp.prototype.toString](https://tc39.es/ecma262/#sec-regexp.prototype.tostring)

### String

- [String.prototype.endsWith](https://tc39.es/ecma262/#sec-string.prototype.endswith)
- [String.prototype.includes](https://tc39.es/ecma262/#sec-string.prototype.includes)
- [String.prototype.match](https://tc39.es/ecma262/#sec-string.prototype.match)
- [String.prototype.matchAll](https://tc39.es/ecma262/#sec-string.prototype.matchall)
- [String.prototype.padEnd](https://tc39.es/ecma262/#sec-string.prototype.padend)
- [String.prototype.padStart](https://tc39.es/ecma262/#sec-string.prototype.padstart)
- [String.prototype.replace](https://tc39.es/ecma262/#sec-string.prototype.replace)
- [String.prototype.search](https://tc39.es/ecma262/#sec-string.prototype.search)
- [String.prototype.split](https://tc39.es/ecma262/#sec-string.prototype.split)
- [String.prototype.startsWith](https://tc39.es/ecma262/#sec-string.prototype.startswith)
- [String.prototype.trim](https://tc39.es/ecma262/#sec-string.prototype.trim)
- [String.prototype.trimEnd](https://tc39.es/ecma262/#sec-string.prototype.trimend)
- [String.prototype.trimStart](https://tc39.es/ecma262/#sec-string.prototype.trimstart)

### Symbol

- [Symbol](https://tc39.es/ecma262/#sec-symbol-constructor)
- [Symbol.prototype.description](https://tc39.es/ecma262/#sec-symbol-prototype.description)
- [Symbol.asyncIterator](https://tc39.es/ecma262/#sec-symbol.asynciterator)
- [Symbol.hasInstance](https://tc39.es/ecma262/#sec-symbol.hasinstance)
- [Symbol.isConcatSpreadable](https://tc39.es/ecma262/#sec-symbol.isconcatspreadable)
- [Symbol.match](https://tc39.es/ecma262/#sec-symbol.match)
- [Symbol.matchAll](https://tc39.es/ecma262/#sec-symbol.matchall)
- [Symbol.replace](https://tc39.es/ecma262/#sec-symbol.replace)
- [Symbol.search](https://tc39.es/ecma262/#sec-symbol.search)
- [Symbol.species](https://tc39.es/ecma262/#sec-symbol.species)
- [Symbol.split](https://tc39.es/ecma262/#sec-symbol.split)
- [Symbol.toPrimitive](https://tc39.es/ecma262/#sec-symbol.toprimitive)
- [Symbol.toStringTag](https://tc39.es/ecma262/#sec-symbol-prototype.tostringtag)

## 模块系统

在开发 Lynx 项目时，开发者可封装和引用 JS 模块。

模块现在支持 [ESModule](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) 和 [CommonJS](https://en.wikipedia.org/wiki/CommonJS) 规范的模块系统。ESModule 和 CommonJS 可以混用。

推荐使用 ESModule，能够更好地进行 [TreeShaking](https://webpack.js.org/guides/tree-shaking/)。

### 模块名

无论使用什么模块，都需要指定模块名。模块名可以是：

- 一个相对路径：`./common.js`
- 一个 npm 包名：`lodash`（不支持依赖 C++ addon，不支持依赖 NodeJS 的内置库）
- 经过 [alias](/next/zh/api/build/source/alias.md) 处理的路径：`@common/foo.js`

### CommonJS

CommonJS 使用 `require(path)` 来引入一个模块。使用 `module.exports` 或 `exports` 来导出一个模块。

**common.js**

```js title="common.js" {1,10-11}
const lodash = require('lodash'); // can require npm packages
function hello(name) {
  console.log(`Hello ${lodash.capitalize(name)} !`);
}

function goodbye(name) {
  console.log(`Goodbye ${name} !`);
}

module.exports.hello = hello;
exports.goodbye = goodbye;
```

**ReactLynx**

```jsx {1,6,10}
const { Component } = require('@lynx-js/react'); // can require npm packages

export default App extends Component {
  constructor(props) {
    super(props);
    const common = require('./common.js'); // can require relative path
    common.hello('world');
  }
  componentDidMount() {
    const common = require('./common.js'); // can require relative path
    common.goodbye('world');
  }
  render() {
    return <view><text>Hello, world!</text></view>;
  }
}
```

:::tip

- `require` 可以出现在代码的任何位置，不需要在顶部。

- `require` 一个模块，会**同步**执行该模块内的代码。

- `require` 会缓存返回的对象，对同一路径多次 `require`，会返回**同一个对象**。即：

```js
require('foo') === require('foo'); // true
```

:::

### ESModule

ESModule 使用 `import` 来引入一个模块。使用 `export` 来导出一个模块。
`import` 和 `export` 必须位于代码的**最外层**。

同时 ESModule 可以使用 `import()` 来进行动态导入模块。

**utils.js**

```js title="utils.js"
export function getAge() {
  return 11;
}

export default function (add1, add2) {
  return add1 + add2;
}
```

**ReactLynx**

```jsx {1-2,8,13}
import { Component } from '@lynx-js/react'; // can import npm packages
import { capitalize } from 'lodash';

export default App extends Component {
  constructor(props) {
    super(props);
    // can dynamic import relative path
    import('./utils.js').then(utils => {
      capitalize(utils.getSum());
    });
  }
  async componentDidMount() {
    const utils = await import('./utils.js'); // can dynamic import relative path
    utils.getAge();
  }
  render() {
    return <view><text>Hello, world!</text></view>;
  }
}
```
