1- Default Parameters
當傳入 function 的參數沒有給值時,防止 expection 出現的方法是設定預設值,es6 比起 es5 的使用方法更快:
var link = function(height = 50, color = ‘red’, url = ‘http://azat.co') { … }
2- Template Literals
在字串 (string) 內嵌入變數時,ES5 必須把字串拆散,把變數通過 + 操作加入字串; ES6 容許通過語法 ${val} 嵌入到字串中:
// es5
// var name = ‘Your name is ‘ + first + ‘ ‘ + last + ‘.’
var name = `Your name is ${first} ${last}.`
3- Multi-line Strings
ES6 可以通過 backticks (鍵盤左上角,數字1旁邊)代替 ‘ ,進行多行的字串輸入:
// es5 // var name = ‘first line’ // + ‘second line’ var name = `first line second line`
4- Destructuring Assignment
ES6中,通過簡單的 value assignment, 把 array 內的第 n 值assign 到變數, 或 object 內對應的 key的值 assign 到變數:
//object[a, b, …rest] = [1, 2, 3, 4, 5]; console.log(a); // 1 console.log(b); // 2 console.log(rest); // [3, 4, 5]
//object
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
5- Object Literals
ES6 的 Object 定義變得清楚而且簡短,通過提供縮寫語法:function 定義和初始化參數。也提供 property keys 的初始值運算(computed property keys):
function getCar(make, model, value) {
return {
// with property value shorthand
// syntax, you can omit the property
// value if key matches variable
// name
make, // same as make: make
model, // same as
model: model
value, // same as value: value
// computed values now work with
// object literals
[‘make’ + make]: true,
// Method definition shorthand syntax
// omits `function` keyword & colon
depreciate() {
this.value -= 2500;
}
};
}
let car = getCar(‘Kia’, ‘Sorento’, 40000);
6- Arrow Functions
Arrow function expression,也是所謂的 fat arrow function,最初流行在 coffeescript 的語法中,現在可以在 Javascript 上使用。它最令人興𡚒的是對 this 的行為修正,this 只會對當前function 的內容有效 mozilla.org:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// 等於 : => { return expression; }
// 只有一個參數時,括號才能不加:
(singleParam) => { statements }
singleParam => { statements }
//若無參數,就一定要加括號:
() => { statements }
7- Promises
Promises 的使用一直在 Javascript 上有大量的爭議性,市面上有大量的代替品例如 async, generators, callbacks etc. 它們處理的問題都一樣,非同步 function。單是Promises就很有很多套成熟的代替品: q, bluebird, deferred.js, vow, avow, jquery deferred etc。
ES6對各第三方 Library 的不同Promises 用方製訂了一套標準,而且結合 arrow function 的使用提高它的可讀性和簡短性。即使後來ES7的明日之星 Async/Await處理和 Promise相同的問題,Promise 并沒有因些被搶生意,因為 Async/Await 都是通過 Promise 創建的 Object:
var wait1000 = () => new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
wait1000()
.then(function() {
console.log(‘Yay!’)
return wait1000()
})
.then(function() {
console.log(‘Wheeyee!’)
});
8- Let & Const, Block-Scoped
— Let 只會在目前的 { }內有效,而且重覆定義時會 throw Error 提示 ;
— Const 只會在目前的 { }內有效,定義時必須 initialize,而且不能更改 :
function letExample(value) {
if (value) {
let letValue = value;
console.log(‘inside block’, letValue);
// [SyntaxError] redeclaration of letValue would be a SyntaxError
let letValue = ‘foo’;
}
try {
// [SyntaxError] Accessing letValue is a Reference Error because it
// was defined w/in if-block
console.log(letValue); // if we get here, it means that the JS engine didn’t // throw an exception, which means that the engine // (or transpiled code) did not faithfully reproduce // how let should work
console.log(‘let not faithfully handled’);
} catch (e) {
// e is a ReferenceError
console.log(‘letValue not accessible’, e);
}
}
letExample(2);
9- Classes
如果你是 oop 的忠實粉絲你一定會喜歡ES6為 oop 用戶設推出的 classes feature ,運用 prototype 和 function 實用出類似具有 inheritance 結構的的類別(和傳統 java, python 的類別有差別):
- 定義和實體化 Classes
- 通過 extends 創建 subclasses
- 通過 super 呼叫 parent Object
- 四個重要 methods
- Constructors
- Static methods
- Prototype methods
- Symbol methods (unique & private)
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ‘makes a noise.’);
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ‘roars.’);
}
}
10- Module
在AMD, RequireJS, CommonJS 和其他JS framework 的演變下,具 import 和 export 的module 功能終於在ES6出生了:
Export
export var port = 3000
export function getAccounts(url) {
…
}
Import
import {port, getAccounts} from ‘module’
console.log(port) // 3000
沒有留言:
張貼留言