var a = function(m,n){ var m = m || 50; var n = n || 'es'; //... }
變爲直接放在函數簽名中,由於若是參數爲0,在JavaScript中爲falsejson
var a = function(m=50,n='es'){ //do something }
規範:設定了默認值的入參,應該放在沒有設置默認值的參數以後segmentfault
var myname = 'wlfsmile'; var yourname = 'youname'; var name = 'your name is'+ yourname +'and my name is'+ myname;
變爲數組
var name = `your name is ${yourname} and my name is ${myname}`;
var [a,b,c]=[11,22,33] console.log(a,b,c)//11 22 33 var [a, ,b] = [1, 2, 3, 4, 5]; console.log(a); // => 1 console.log(b); // => 3
對象promise
var{name,age}={name:"張三",age:"20"} console.log(name,age)//張三 20
解構jsonapp
var jike = {"name":"tom","age":"23","sex":"男"}; var {name,age,sex}=jike; console.log(name,age,sex)//tom 23 男 function cal(a,b){ var ret1 = a+b; var ret2 = a-b; var ret3 = a*b; var ret4 = a/b; return [ret1,ret2,ret3,ret4] } var [r1,r2,r3,r4] = cal(10,5); console.log(r1,r2,r3,r4)//15 5 50 2
//before var obj = { arr: [1, 2, 3, 4, 5, 6], getMaxPow2: function() { var that = this, getMax = function() { return Math.max.apply({}, that.arr); }; return Math.pow(getMax(), 2); } } //after var obj = { arr: [1, 2, 3, 4, 5, 6], getMaxPow2: function() { var getMax = () => { return Math.max.apply({}, this.arr); } return Math.pow(getMax(), 2); } }
注意模塊化
function getSum() { var example = () => { return Array .prototype .reduce .call(arguments, (pre, cur) => pre + cur); } return example(); } getSum(1, 2, 3); // => 6
/* 類不會被提高 */ let puppy = new Animal('puppy'); // => ReferenceError class Animal { constructor(name) { this.name = name; } sleep() { console.log(`The ${this.name} is sleeping...`); } static type() { console.log('This is an Animal class.'); } } let puppy = new Animal('puppy'); puppy.sleep(); // => The puppy is sleeping... /* 實例化後沒法訪問靜態方法 */ puppy.type(); // => TypeError Animal.type(); // => This is an Animal class. /* 實例化前沒法訪問動態方法 */ Animal.sleep(); // => TypeError /* 類不能重複定義 */ class Animal() {} // => SyntaxError
注意函數
class Programmer extends Animal { constructor(name) { /* 在 super 方法以前 this 不可用 */ console.log(this); // => ReferenceError super(name); console.log(this); // Right! } program() { console.log("I'm coding..."); } sleep() { console.log('Save all files.'); console.log('Get into bed.'); super.sleep(); } } let coder = new Programmer('coder'); coder.program(); // => I'm coding... coder.sleep(); // => Save all files. => Get into bed. => The coder is sleeping.
參考ES6 經常使用新特性講解this