想在新版本的 NodeJS 中體驗 ES6(harmony)的新特性嗎?以下整理在不同系統下的啟用方式。
Linux 下啟用
以 Node v0.11.6 為例,先查看有哪些 harmony 相關選項:
$ node --v8-options | grep harm --harmony_typeof (enable harmony semantics for typeof) --harmony_scoping (enable harmony block scoping) --harmony_modules (enable harmony modules (implies block scoping)) --harmony_symbols (enable harmony symbols (a.k.a. private names)) --harmony_proxies (enable harmony proxies) --harmony_collections (enable harmony collections (sets, maps, and weak maps)) --harmony_observation (enable harmony object observation (implies harmony collections) --harmony_typed_arrays (enable harmony typed arrays) --harmony_array_buffer (enable harmony array buffer) --harmony_generators (enable harmony generators) --harmony_iteration (enable harmony iteration (for-of)) --harmony_numeric_literals (enable harmony numeric literals (0o77, 0b11)) --harmony_strings (enable harmony string) --harmony_arrays (enable harmony arrays) --harmony (enable all harmony features (except typeof))
接著可以透過 awk 一次啟用所有 ES6 新特性,需搭配 strict 模式使用:
$ node --use-strict $(node --v8-options | grep harm | awk '{print $1}' | xargs) #ES6 Windows 下啟用(通用方法)
node --harmony app.js
看個例子:作用域
關鍵字 let 能把變數的作用範圍限定在一個程式碼區塊內:
'use strict'; if (1) { let b = 2; console.log(b); //2 } console.log(typeof b); //undefined 可以看到,在區塊內用 let 宣告的變數 b,離開區塊後就無法再存取,這正是 ES6 區塊級作用域帶來的改善。