ES5和ES6-句句經典
什麼是ES5
作為ECMAScript第五個版本(第四版因為過於複雜廢棄了),瀏覽器支援情況可看第一副圖,增加特性如下。
1. strict模式
嚴格模式,限制一些用法,'use strict';
2. Array增加方法
增加了every、some 、forEach、filter 、indexOf、lastIndexOf、isArray、map、reduce、reduceRight方法
PS: 還有其他方法 Function.prototype.bind、String.prototype.trim、Date.now
3. Object方法
Object.getPrototypeOfObject.createObject.getOwnPropertyNamesObject.definePropertyObject.getOwnPropertyDescriptorObject.definePropertiesObject.keysObject.preventExtensions / Object.isExtensibleObject.seal / Object.isSealedObject.freeze / Object.isFrozenPS:只講有什麼,不講是什麼。什麼是ES6
ECMAScript6在保證向下相容的前提下,提供大量新特性,目前瀏覽器相容情況如下:
ES6特性如下:
1.塊級作用域 關鍵字let, 常量const
2.物件字面量的屬性賦值簡寫(property value shorthand)
var obj = { // __proto__ __proto__: theProtoObj, // Shorthand for ‘handler: handler’ handler, // Method definitions toString() { // Super calls return "d " + super.toString(); }, // Computed (dynamic) property names [ 'prop_' + (() => 42)() ]: 42 };
3.賦值解構
let singer = { first: "Bob", last: "Dylan" }; let { first: f, last: l } = singer; // 相當於 f = "Bob", l = "Dylan" let [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec("2015-10-25"); let [x, y] = [1, 2, 3]; // x = 1, y = 2
4.函式引數 - 預設值、引數打包、 陣列展開(Default 、Rest 、Spread)
//Default function findArtist(name='lu', age='26') { ... } //Rest function f(x, ...y) { // y is an Array return x * y.length; } f(3, "hello", true) == 6 //Spread function f(x, y, z) { return x + y + z; } // Pass each elem of array as argument f(...[1,2,3]) == 6
5.箭頭函式 Arrow functions
(1).簡化了程式碼形式,預設return表示式結果。
(2).自動繫結語義this,即定義函式時的this。如上面例子中,forEach的匿名函式引數中用到的this。
6.字串模板 Template strings
var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?` // return "Hello Bob, how are you today?"
7. Iterators(迭代器)+ for..of
迭代器有個next方法,呼叫會返回:
(1).返回迭代物件的一個元素:{ done: false, value: elem }
(2).如果已到迭代物件的末端:{ done: true, value: retVal }
for (var n of ['a','b','c']) { console.log(n); } // 列印a、b、c
8.生成器 (Generators)
9.Class
Class,有constructor、extends、super,但本質上是語法糖(對語言的功能並沒有影響,但是更方便程式設計師使用)。
class Artist { constructor(name) { this.name = name; } perform() { return this.name + " performs "; } } class Singer extends Artist { constructor(name, song) { super.constructor(name); this.song = song; } perform() { return super.perform() + "[" + this.song + "]"; } } let james = new Singer("Etta James", "At last"); james instanceof Artist; // true james instanceof Singer; // true james.perform(); // "Etta James performs [At last]"
10.Modules
ES6的內建模組功能借鑑了CommonJS和AMD各自的優點:
(1).具有CommonJS的精簡語法、唯一匯出出口(single exports)和迴圈依賴(cyclic dependencies)的特點。
(2).類似AMD,支援非同步載入和可配置的模組載入。
// lib/math.js export function sum(x, y) { return x + y; } export var pi = 3.141593; // app.js import * as math from "lib/math"; alert("2π = " + math.sum(math.pi, math.pi)); // otherApp.js import {sum, pi} from "lib/math"; alert("2π = " + sum(pi, pi)); Module Loaders: // Dynamic loading – ‘System’ is default loader System.import('lib/math').then(function(m) { alert("2π = " + m.sum(m.pi, m.pi)); }); // Directly manipulate module cache System.get('jquery'); System.set('jquery', Module({$: $})); // WARNING: not yet finalized
11.Map + Set + WeakMap + WeakSet
四種集合型別,WeakMap、WeakSet作為屬性鍵的物件如果沒有別的變數在引用它們,則會被回收釋放掉。
// 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; //WeakMap 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
12.Math + Number + String + Array + Object APIs
一些新的API
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].find(x => x == 3) // 3 [1, 2, 3].findIndex(x => x == 2) // 1 [1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2] ["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) })
13. Proxies
使用代理(Proxy)監聽物件的操作,然後可以做一些相應事情。
var target = {}; var handler = { get: function (receiver, name) { return `Hello, ${name}!`; } }; var p = new Proxy(target, handler); p.world === 'Hello, world!';
可監聽的操作: get、set、has、deleteProperty、apply、construct、getOwnPropertyDescriptor、defineProperty、getPrototypeOf、setPrototypeOf、enumerate、ownKeys、preventExtensions、isExtensible。
14.Symbols
Symbol是一種基本型別。Symbol 通過呼叫symbol函式產生,它接收一個可選的名字引數,該函式返回的symbol是唯一的。
var key = Symbol("key"); var key2 = Symbol("key"); key == key2 //false
15.Promises
Promises是處理非同步操作的物件,使用了 Promise 物件之後可以用一種鏈式呼叫的方式來組織程式碼,讓程式碼更加直觀(類似jQuery的deferred 物件)。
function fakeAjax(url) { return new Promise(function (resolve, reject) { // setTimeouts are for effect, typically we would handle XHR if (!url) { return setTimeout(reject, 1000); } return setTimeout(resolve, 1000); }); } // no url, promise rejected fakeAjax().then(function () { console.log('success'); },function () { console.log('fail'); });
總結
對於ES6,在某些方式是不是重蹈ES4的覆轍,變得複雜了;又或許幾年後大家的接受能力變強了,覺得是應該這樣了。我覺得還是不錯的,因為它們是向下相容的,即使複雜語法不會用,也能用自己熟知的方式,提供的語法糖也都挺實際。