es6学习-函数的扩展
1.函数默认值,在es6之前是使用||来赋默认值,在es6中可以直接在括号中进行赋值
//es6可以直接在括号中赋值 function show(a,b=8){ //es6之前,如果b没有值则使用8 //b=b||8; return a+b; } alert(show(5));
2.箭头函数,相当于匿名函数
//箭头函数(参数列表)=>返回值 //var show=(a,b=7)=>a+b; //多行代码使用{}进行包裹 var show=(a,b=7) => { console.log('调用了一次'); return a+b; } alert(show(1));
3.this,在es6中this始终只方法定义时的this。
var obj={ a:5, fun:function(){ console.log(this.a); }, test:function(){ console.log(this);// this ---> obj /* setTimeout(function(){ console.log(this);//this ---> window this.fun(); },1) */ setTimeout(()=>{ this.fun();//this ---> obj },1); } } obj.test();
说白了,在箭头函数定义的方法中使用this不是值当前对象,而是只父函数所在的对象。