文章目录
一、介绍
箭头函数是es6当中对函数的一种全新表示法。先来看一个最简单的箭头函数
let fn = v=>v;
console.log(fn("1"));//1
该箭头函数等同于
let fn = function(v){
return v;
}
console.log(fn("1"))
二、语法
1. 如果只有一条语句,可以把 { } 和 return 省略掉
v=>v+v;
//相当于
function (v){.
return v+v;
}
2. 如果语句为多条,则 { } 和 return 不可以省略
v=>{
var sum=0;
for(let i=0;i<v;i++){
sum+=i;
}
return sum;
}
3. 当没有参数或有多个参数时,需要用括号()括起来
(num1,num2)=>num1+num2;
4. 当省略 { } 和 return 时,如果返回的内容是一个对象,对象需要用括号()括起来
()=>({name:"laoliu"});
三、箭头函数和传统函数的区别
1. 箭头函数不能用于构造函数
//传统的构造函数
var Box = function(age){
this.myAge = age
}
var _box = new Box(20)
console.log(_box.myAge);//20
//改为箭头函数形式
var Box = age=>{
this.myAge = age
}
var _box = new Box(20)
console.log(_box.myAge);//Box is not a constructor
2. 箭头函数没有prototype属性
var Foo = ()=>{}
console.log(Foo.prototype);//undefined
3. 箭头函数不绑定arguments
在使用箭头函数时,arguments 指向的对象并不是当前函数所属的argments,而是上级函数的arguments
var arguments = 40;
var fn = ()=>arguments;
console.log(fn());//40
function foo(){
var f = i=>arguments[0]+i;
return f(2);
}
console.log(foo(1));//3
4. 箭头函数不绑定this
箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象
window.color = "red";
//let 声明的全局变量不具有全局属性,即不能用window.访问
let color = "green";//var color = "green",则输出都为green
let obj = {
color: "blue",
getColor: () => {
return this.color;//this指向window
}
};
let sayColor = () => {
return this.color;//this指向window
};
obj.getColor();//red
sayColor();//red
5. 箭头函数无法使用 call()或 apply()来改变其运行的作用域
window.color = "red";
let color = "green";
let obj = {
color: "blue"
};
let sayColor = () => {
return this.color;
};
sayColor.apply(obj);//red