ES2015 概覽

一底燎、簡介
ECMAScript 2015 是在 2015 年 6 月獲批的 ECMAScript 標準。對 ECMAScript 來說,ES2015 是一個巨大的更新遏乔,第一次這樣大的更新是在 2009 年式曲。在主流 JavaScript 引擎中實現(xiàn) ES2015 中特性的工作目前正在如火如荼地進行妨托。
ES2015 特性

二、ES2015 特性
1吝羞、Arrows and Lexical This
Arrows are a function shorthand using the => syntax.
arrows 使用“=>”格式兰伤,是一種函數(shù)簡寫。
<code>
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
// Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
// Lexical this
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f => console.log(this._name + " knows " + f));
}
};
// Lexical arguments
function square() {
let example = () => {
let numbers = [];
for (number of arguments) {
numbers.push(number * 2);
}
return numbers;
};
return example();
}
square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 8, 15, 16, 23, 42]
</code>

2钧排、Classes(一種語法糖)
ES2015 classes are a simple sugar over the prototype-based OO pattern.
<code>
class SkinnedMesh extends THREE.Mesh {
constructor(geometry, materials) {
super(geometry, materials);
this.idMatrix = SkinnedMesh.defaultMatrix();
this.bones = [];
this.boneMatrices = [];
//...
}
update(camera) {
//...
super.update();
}
static defaultMatrix() {
return new THREE.Matrix4();
}
}
</code>

3敦腔、Enhanced Object Literals
Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods and making super calls. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.
<code>
var obj = {
// Sets the prototype. "proto" or 'proto' would also work.
proto: theProtoObj,
// Computed property name does not set prototype or trigger early error
for duplicate proto properties.
<code>['proto']: somethingElse, </code>
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ "prop_" + (() => 42)() ]: 42
};
</code>

4、Template Strings(也是一種語法糖)
Template strings provide syntactic sugar for constructing strings.
<code>
// Basic literal string creation
This is a pretty little template string.
// Multiline strings
In ES5 this is not legal.
// Interpolate variable bindings
var name = "Bob", time = "today";
Hello ${name}, how are you ${time}
// Unescaped template strings
String.rawIn ES5 "\n" is a line-feed.
// Construct an HTTP request prefix is used to interpret the replacements and construction
GEThttp://foo.org/bar?a=${a}&b=$卖氨 Content-Type: application/json X-Credentials: ${credentials} { "foo": ${foo}, "bar": ${bar}}(myOnReadyStateChangeHandler);
</code>

5会烙、Destructuring(解構(gòu))
允許模式匹配,支持對象和數(shù)組匹配筒捺。
<code>
// list matching
var [a, ,b] = [1,2,3];
a === 1;
b === 3;
// object matching
var { op: a, lhs: { op: b }, rhs: c }
= getASTNode()
// object matching shorthand
// binds op, lhs and rhs in scope
var {op, lhs, rhs} = getASTNode()
// Can be used in parameter position
function g({name: x}) {
console.log(x);
}
g({name: 5})
// Fail-soft destructuring
var [a] = [];a === undefined;
// Fail-soft destructuring with defaults
var [a = 1] = [];
a === 1;
// Destructuring + defaults arguments
function r({x, y, w = 10, h = 10}) {
return x + y + w + h;
}
r({x:1, y:2}) === 23
</code>

6柏腻、Default + Rest + Spread
Callee-evaluated default parameter values.
在函數(shù)回調(diào)中,把數(shù)組轉(zhuǎn)換成連續(xù)參數(shù)
<code>
function f(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;}
f(3) == 15
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
</code>

7系吭、Let + Const
let is the new var. const is single-assignment.
<code>
function f() {
{
let x;
{
// this is ok since it's a block scoped name
const x = "sneaky";
// error, was just defined with const above
x = "foo";
}
// this is ok since it was declared with let
x = "bar";
// error, already declared above in this block
let x = "inner";
}
}
</code>

8五嫂、Iterators + For..Of
<code>
let fibonacci = {
Symbol.iterator {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
</code>
Iteration is based on these duck-typed interfaces
<code>
interface IteratorResult {
done: boolean;
value: any;
}
interface Iterator {
next(): IteratorResult;
}
interface Iterable {
Symbol.iterator: Iterator
}
</code>

9、Generators
Generators simplify iterator-authoring using function* and yield.
聲明為 function* 的函數(shù)返回一個 Generator 實例。Generator 是 iterators 的子類型沃缘,它包含 next 和 throw 躯枢。這使得值可以回滾進 generator. 因此,yield 是返回一個值或扔掉一個值的表達槐臀。
<code>
var fibonacci = {
[Symbol.iterator]: function*() {
var pre = 0, cur = 1;
for (;;) {
var temp = pre;
pre = cur;
cur += temp;
yield cur;
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
interface Generator extends Iterator {
next(value?: any): IteratorResult;
throw(exception: any);
}
</code>

三锄蹂、深度理解
1、Unicode
<code>
// same as ES5.1
"??".length == 2
// new RegExp behaviour, opt-in ‘u’
"??".match(/./u)[0].length == 2
// new form
"\u{20BB7}" == "??" == "\uD842\uDFB7"
// new String ops
"??".codePointAt(0) == 0x20BB7
// for-of iterates code points
for(var c of "??") {
console.log(c);
}
</code>

2水慨、Modules
<code>
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
console.log("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
console.log("2π = " + sum(pi, pi));
// lib/mathplusplus.js
export * from "lib/math";
export var e = 2.71828182846;
export default function(x) {
return Math.exp(x);
}
// app.js
import exp, {pi, e} from "lib/mathplusplus";
console.log("e^π = " + exp(pi));
</code>

3得糜、Module Loaders
babel 默認使用 commonJS
<code>
// Dynamic loading – ‘System’ is default loader
System.import("lib/math").then(function(m)
{
alert("2π = " + m.sum(m.pi, m.pi));
});
// Create execution sandboxes – new Loaders
var loader = new Loader({
global: fixup(window)
// replace ‘console.log’
});
loader.eval("console.log("hello world!");");
// Directly manipulate module cache
System.get("jquery");
System.set("jquery", Module({$: $})); // WARNING: not yet finalized
</code>

4、Map + Set + WeakMap + WeakSet(面向常用算法/程序的有效數(shù)據(jù)結(jié)構(gòu))
<code>
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set
</code>

5晰洒、Proxies
<code>
// Proxying a normal object
var target = {};
var handler = {
get: function (receiver, name) {
return Hello, ${name}!;
}
};
var p = new Proxy(target, handler);
p.world === "Hello, world!";
// Proxying a function object
var target = function () { return "I am the target"; };
var handler = {
apply: function (receiver, ...args) {
return "I am the proxy";
}
};
var p = new Proxy(target, handler);
p() === "I am the proxy";
var handler ={
// target.prop
get: ...,
// target.prop = value
set: ...,
// 'prop' in target
has: ...,
// delete target.prop
deleteProperty: ...,
// target(...args)
apply: ...,
// new target(...args)
construct: ...,
// Object.getOwnPropertyDescriptor(target, 'prop') getOwnPropertyDescriptor: ...,
// Object.defineProperty(target, 'prop', descriptor)
defineProperty: ..., // Object.getPrototypeOf(target), Reflect.getPrototypeOf(target), // target.proto, object.isPrototypeOf(target), object instanceof target getPrototypeOf: ..., // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target) setPrototypeOf: ...,
// for (let i in target) {}
enumerate: ...,
// Object.keys(target)
ownKeys: ...,
// Object.preventExtensions(target)
preventExtensions: ...,
// Object.isExtensible(target)
isExtensible :...
}
</code>

6朝抖、Symbols
Symbols enable access control for object state. Symbols 可以獲取對象狀態(tài)的控制權(quán)。Symbols are a new primitive type. 可選項 name 用來 debug,不是自身屬性的一部分谍珊。symbol 不是私有的治宣,它們可以通過類似 Object.getOwnPropertySymbols 的特性暴露出來。
<code>
(function() {
// module scoped symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
doStuff: function() {
... this[key] ...
}
};
// Limited support from Babel, full support requires native implementation.
typeof key === "symbol"
})();
var c = new MyClass("hello")
c["key"] === undefined
</code>

7砌滞、Subclassable Built-ins
In ES2015, built-ins like Array, Date and DOM Elements can be subclassed.
<code>
// User code of Array
subclassclass MyArray extends Array
{
constructor(...args) {
super(...args); }
}
var arr = new MyArray();
arr[1] = 12;
arr.length == 2
</code>

8侮邀、Math + Number + String + Object APIs
<code>
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll("*")) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7][1,2,3].findIndex(x => x == 2) // 1
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"
Object.assign(Point, { origin: new Point(0,0) })
</code>

9、Binary and Octal Literals
Two new numeric literal forms are added for binary (b) and octal (o).
<code>
0b111110111 === 503 // true
0o767 === 503 // true
</code>

10布持、Promises
Promises are a library for asynchronous programming.
<code>
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
var p = timeout(1000).then(() => {
return timeout(2000);
}).then(() => {
throw new Error("hmm");
}).catch(err => {
return Promise.all([timeout(100), timeout(200)]);
})
</code>

11豌拙、Reflect API(對實現(xiàn) proxy 很有用)
<code>
var O = {a: 1};
Object.defineProperty(O, 'b', {value: 2});
O[Symbol('c')] = 3;
Reflect.ownKeys(O); // ['a', 'b', Symbol(c)]
function C(a, b){
this.c = a + b;
}
var instance = Reflect.construct(C, [20, 22]);
instance.c; // 42
</code>

12、Tail Calls
<code>
function factorial(n, acc = 1) {
"use strict";
if (n <= 1)
return acc;
return factorial(n - 1, n * acc);
}
// Stack overflow in most implementations today,// but safe on arbitrary inputs in ES2015
factorial(100000)
</code>

參考鏈接:https://babeljs.io/docs/learn-es2015/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末题暖,一起剝皮案震驚了整個濱河市按傅,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌胧卤,老刑警劉巖唯绍,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異枝誊,居然都是意外死亡况芒,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進店門叶撒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绝骚,“玉大人,你說我怎么就攤上這事祠够⊙雇簦” “怎么了?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵古瓤,是天一觀的道長止剖。 經(jīng)常有香客問我腺阳,道長,這世上最難降的妖魔是什么穿香? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任亭引,我火速辦了婚禮,結(jié)果婚禮上皮获,老公的妹妹穿的比我還像新娘焙蚓。我一直安慰自己,他們只是感情好洒宝,可當我...
    茶點故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布主届。 她就那樣靜靜地躺著,像睡著了一般待德。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上枫夺,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天将宪,我揣著相機與錄音,去河邊找鬼橡庞。 笑死较坛,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的扒最。 我是一名探鬼主播丑勤,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼吧趣!你這毒婦竟也來了法竞?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤强挫,失蹤者是張志新(化名)和其女友劉穎岔霸,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體俯渤,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡呆细,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了兽埃。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片虹钮。...
    茶點故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡壶硅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出坑夯,到底是詐尸還是另有隱情,我是刑警寧澤劝萤,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布渊涝,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏跨释。R本人自食惡果不足惜胸私,卻給世界環(huán)境...
    茶點故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鳖谈。 院中可真熱鬧岁疼,春花似錦、人聲如沸缆娃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贯要。三九已至暖侨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間崇渗,已是汗流浹背字逗。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留宅广,地道東北人葫掉。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像跟狱,于是被迫代替她去往敵國和親俭厚。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,442評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗驶臊。 張土汪:刷leetcod...
    土汪閱讀 12,747評論 0 33
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理挪挤,服務(wù)發(fā)現(xiàn),斷路器关翎,智...
    卡卡羅2017閱讀 134,695評論 18 139
  • 我是從一篇介紹LSM原理的文章的擴展閱讀部分电禀,找到這篇文章的。前者的作者稱笤休,后者對LSM的原理做了非常精彩的介紹尖飞。...
    古小黎閱讀 1,025評論 0 1
  • 今天是最無意識的一天。 二熊出現(xiàn)后店雅,腦子就一片空白了政基。 直到我坐公車回到賓館,我都沉默不發(fā)闹啦。 我高興不起來沮明,不知道...
    不正常生物研究中心閱讀 389評論 0 15
  • -----<王家衛(wèi)的色彩世界> “因為你我會記住那一分鐘〗。” ...
    檸檬不戀酸閱讀 707評論 0 3