介紹
ECMAScript 6 在接下來的一段時間內(nèi)將成為 ECMAScript的一個標(biāo)準(zhǔn)陕悬。這個標(biāo)準(zhǔn)預(yù)計在今年的時候就會被簽署暮蹂,不管在Github,還是在很多社區(qū)钙皮,javascript愛好者已經(jīng)早已開始擁抱變化澎现,享受ES6 帶來的美好,這篇文章將介紹ES6的一些新特性延蟹。由于ES6 還沒有很好地被瀏覽器支持伏社,所以這篇文章的ES6代碼將使用 Babel 進(jìn)行編譯抠刺。
ECMAScript 6 的新特性
箭頭(Arrow)
=>是function的簡寫形式塔淤,支持expression和 statement 兩種形式。同時一點(diǎn)很重要的是它擁有詞法作用域的this值矫付,幫你很好的解決this的指向問題凯沪,這是一個很酷的方式,可以幫你減少一些代碼的編寫买优,先來看看它的語法妨马。
([param] [, param]) => {
statements
}
param => expression
類(class)
ES6 引入了class(類),讓javascript的面向?qū)ο缶幊套兊酶尤菀浊逦腿菀桌斫馍庇n愔皇腔谠偷拿嫦驅(qū)ο竽J降恼Z法糖烘跺。
class Animal { // 構(gòu)造方法,實(shí)例化的時候?qū)徽{(diào)用脂崔,如果不指定滤淳,那么會有一個不帶參數(shù)的默認(rèn)構(gòu)造函數(shù).
constructor(name,color) {
this.name = name;
this.color = color;
}
// toString 是原型對象上的屬性
toString() {
console.log('name:' + this.name + ',color:' + this.color);
}
}
var animal = new Animal('dog','white');
animal.toString();
console.log(animal.hasOwnProperty('name')); //true
console.log(animal.hasOwnProperty('toString')); // false
console.log(animal.__proto__.hasOwnProperty('toString')); // true
class Cat extends Animal {
constructor(action) {
// 子類必須要在constructor中指定super 方法,否則在新建實(shí)例的時候會報錯.
// 如果沒有置頂consructor,默認(rèn)帶super方法的constructor將會被添加砌左、
super('cat','white');
this.action = action;
}
toString() {
console.log(super.toString());
}
}
var cat = new Cat('catch')
cat.toString();
// 實(shí)例cat 是 Cat 和 Animal 的實(shí)例脖咐,和Es5完全一致。
console.log(cat instanceof Cat); // true
console.log(cat instanceof Animal); // true