跳到主要內容

JavaScript 環境

JavaScript 執行階段

當使用 React Native 時,您的 JavaScript 程式碼將會在最多三個環境中執行

  • 在大多數情況下,React Native 將使用 Hermes,這是一個為 React Native 優化的開源 JavaScript 引擎。
  • 如果 Hermes 被禁用,React Native 將使用 JavaScriptCore,這是 Safari 使用的 JavaScript 引擎。請注意,在 iOS 上,由於 iOS 應用程式中缺少可寫入的可執行記憶體,因此 JavaScriptCore 不使用 JIT。
  • 當使用 Chrome 除錯時,所有 JavaScript 程式碼都在 Chrome 本身內執行,並透過 WebSockets 與原生程式碼通信。Chrome 使用 V8 作為其 JavaScript 引擎。

雖然這些環境非常相似,但您可能會遇到一些不一致之處。最好避免依賴任何執行階段的特定細節。

JavaScript 語法轉換器

語法轉換器讓編寫程式碼更加愉快,因為它們允許您使用新的 JavaScript 語法,而無需等待所有直譯器都支援。

React Native 隨附 Babel JavaScript 編譯器。請查看 Babel 文件以了解有關其支援轉換的更多詳細資訊。

React Native 啟用的完整轉換列表可以在 @react-native/babel-preset 中找到。

轉換程式碼
ECMAScript 5
保留字
promise.catch(function() {...});
ECMAScript 2015 (ES6)
箭頭函式
<C onPress={() => this.setState({pressed: true})} />
區塊作用域
let greeting = 'hi';
呼叫展開
Math.max(...array);
類別
class C extends React.Component {render() { return <View />; }}
計算屬性
const key = 'abc'; const obj = {[key]: 10};
常數
const answer = 42;
解構
const {isActive, style} = this.props;
for…of
for (var num of [1, 2, 3]) {...};
函式名稱
let number = x => x;
字面量
const b = 0b11; const o = 0o7; const u = 'Hello\u{000A}\u{0009}!';
模組
import React, {Component} from 'react';
物件簡潔方法
const obj = {method() { return 10; }};
物件簡寫表示法
const name = 'vjeux'; const obj = {name};
參數
function test(x = 'hello', {a, b}, ...args) {}
其餘參數
function(type, ...args) {};
簡寫屬性
const o = {a, b, c};
黏性正則表達式
const a = /o+/y;
模板字面量
const who = 'world'; const str = `Hello ${who}`;
Unicode 正則表達式
const string = 'foo💩bar'; const match = string.match(/foo(.)bar/u);
ECMAScript 2016 (ES7)
指數運算符
let x = 10 ** 2;
ECMAScript 2017 (ES8)
Async Functions
async function doStuffAsync() {const foo = await doOtherStuffAsync();};
函式尾隨逗號
function f(a, b, c,) {};
ECMAScript 2018 (ES9)
物件展開
const extended = {...obj, a: 10};
ECMAScript 2019 (ES10)
可選的 Catch Binding
try {throw 0; } catch { doSomethingWhichDoesNotCareAboutTheValueThrown();}
ECMAScript 2020 (ES11)
動態導入
const package = await import('package'); package.function()
Nullish Coalescing 運算符
const foo = object.foo ?? 'default';
可選鏈式調用
const name = obj.user?.name;
ECMAScript 2022 (ES13)
類別欄位
class Bork {static a = 'foo'; static b; x = 'bar'; y;}
Stage 1 Proposal
Export Default From
export v from 'mod';
其他
Babel 模板
template(`const %%importName%% = require(%%source%%);`);
Flow
function foo(x: ?number): string {};
ESM 轉 CJS
export default 42;
JSX
<View style={{color: 'red'}} />
Object Assign
Object.assign(a, b);
React 顯示名稱
const bar = createReactClass({});
TypeScript
function foo(x: {hello: true, target: 'react native!'}): string {};

Polyfills

許多標準函式在所有支援的 JavaScript 執行階段中也可用。

瀏覽器

ECMAScript 2015 (ES6)

ECMAScript 2016 (ES7)

ECMAScript 2017 (ES8)

特定

  • __DEV__