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