源链接地址https://www.cnblogs.com/sun-web/p/10729582.html
1、箭头函数介绍
//ES6<br> let fn=v=>v; console.log(fn("好酷的箭头函数!"));//好酷的箭头函数! //ES5<br> let fn=function(v){ return v; } console.log(fn("好酷的箭头函数!"));//好酷的箭头函数!
2、写法
如果只有一条语句,可以将{}和return省略掉
v=>v+v; //相当于 function (v){. return v+v; }
如果语句为多条,则不可以省略{}和return
v=>{ var sum=0; for(let i=0;i<v;i++){ sum+=i; } return sum; }
当没有参数或有多个参数时,需要用括号()括起来:
(num1,num2)=>num1+num2;
当省略{}和return时,如果返回的内容是一个对象,对象需要用括号()括起来
()=>({name:"laoliu"});
箭头函数不能用于构造函数
//正常情况 var Box=function(age){ this.myAge=age; } var obj=new Box(20); console.log(obj.myAge);//20 //箭头函数 var Box=age=>{ this.myAge=age; } var obj=new Box(20);//Box is not a constructor console.log(obj.myAge);
箭头函数没有prototype属性
var Foo = () => {}; console.log(Foo.prototype); // undefined
箭头函数不绑定arguments
var arguments = 42; var fn = () => arguments; console.log(fn()); // 42 function foo() { var f = (i) => arguments[0]+i; return f(2); } console.log(foo(1)); // 3
箭头函数不绑定this
window.color = "red"; //let 声明的全局变量不具有全局属性,即不能用window.访问 let color = "green"; let obj = { color: "blue", getColor: () => { return this.color;//this指向window } }; let sayColor = () => { return this.color;//this指向window }; obj.getColor();//red sayColor();//red
window.color = "red"; let color = "green"; let obj = { color: "blue" }; let sayColor = () => { return this.color; }; sayColor.apply(obj);//red