ES6新标对函数的改革绝对让人眼前一亮,箭头函数太有逼格了,参数结合三点运算符,真他么简洁!!!
function add(x,y){return x+y};
var add=(x,y)=>x+y;
add(1,2);
var fun1=x=>x+1;
fun1(3);
['a','b','c'].map(x=>x);
var fun2=(...args)=>{
for(let arg of args){
console.log(arg)
}
};
fun2(1,2,3);
es6提倡的简洁理念在箭头函数得到最大体现,未来箭头函数一定会替代传统函数…. |
let obj1={fun:function(){
setTimeout(function(){console.log(this)})
}};
obj1.fun();
obj2={fun:function(){
setTimeout(()=>console.log(this))
}};
obj2.fun();
箭头函数体内的this指向的是定义时所在的对象,而不是执行时所在的对象。箭头函数绑定this的指向,很大程度解决了过去this动态指向的困扰,可以大大减少显示绑定this对象的写法(call,apply,bind)。 |
function fun1(x='a'){console.log(x)};
fun1();
let fun2=(x=1,y=2)=>x+y;
fun2();
fun2(10);
fun2(2,5);
fun2(4,5,6);
let fun3=function(x=1,y=2){this.x=x;this.y=y}
let newFun=new fun3;
let fun4=({x,y=2})=>console.log(x,y)
fun4();
fun4({});
fun4({x:2,y:4});
fun4({x:2});
let fun5=(x,y)=>{let x=5;return x};