下面是個人比較喜歡的es6的新特性
終於來了!!
Template Literals
`Fifteen is ${a + b} and not ${2 * a + b}.`
Arrow Functions
function Person() {
this.age = 0;
// var self = this;
// 定義該 Arrow Functions 時的環境,是在 Person 物件中
setInterval(() => {
// 所以 this 會正確指向 Person 物件
this.age++;
//self.age++
}, 1000);
}
var p = new Person();
class syntax sugar
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
static triple(n) {
if (n === undefined) {
n = 1;
}
return n * 3;
}
}
class Dog extends Animal {
constructor(name) {
super(name)
this.name = name;
}
speak() {
super.speak() // this會用到子類別的obj
console.log(this.name + ' barks.');
}
static triple(n) {
return super.triple(n) * super.triple(n);
}
}
var d = new Dog('Mitzie');
// 顯示 Mitzie barks.
d.speak();
import & export
// export [default] <exp with var>
// var ..., function, class
export { encrypt };
export { decrypt as dec };
import {aString, aObject, aFunction, aClass} from './lib.js'
import * as myModule from './lib.js'
有趣的特性
Computed property keys
var prefix = 'es6';
var obj = {
// 計算屬性
[prefix + ' is']: 'cool',
// 計算方法
[prefix + ' score']() {
console.log(100);
}
};
// 顯示 cool
console.log(obj['es6 is']);
// 顯示 100
obj['es6 score']();
preteier & eslint
preteier => 讓code好看 eslint => 檢查coding style
vscode設定 prettier ESLint eslint-config-airbnb Prettier-eslint 用上面三個plugin後,先跑prettier再跑ESLint