1、箭头函数语法上比普通函数简洁
//普通函数
function fn(){}
//箭头函数
let fn = () => {}
2、箭头函数的this指向和普通函数不同
普通函数的this一般指向的是调用它的对象:
function a(){
console.log(this);
}
a(); //window
//上面的a() <====> window.a()
//而且普通函数的this还是指向离它近的对象,如下:
var b = {
c:{
d:function(){console.log(this)}
}
}
b.c.d();//这里指向的是c -> {d:function(){}},所以是指向离的近的对象
箭头函数没有自己的this, 它的this是继承而来, 默认指向在定义它时所处的对象,而且使用call/apply等方式都无法改变this的指向:
//先要知道对于延时函数(setTimeout/setInterval)内部的回调函数的this指向全局对象window
function fn(){
setTimeout(function(){console.log(this);},1000); // 延时函数 -> window
setTimeout(() => {console.log(this);},1000); //箭头函数这里的this指向定义时所处的对象,也就是fn
setTimeout(function(){
setTimeout(function(){console.log(this);},1000);//延时函数 -> window
console.log(this); //延时函数 -> window
setTimeout(() => {console.log(this);},1000);//外层的this是处于window,而箭头函数指向定义时所处的对象,所以就是window
},1000);
setTimeout(() => {
setTimeout(function(){console.log(this);},1000);//延时函数 -> window
console.log(this); //箭头函数 -> fn
setTimeout(() => {console.log(this);},1000);//外层的this是处于fn,而箭头函数指向定义时所处的对象,所以就是fn
},1000);
}
new fn();//会执行fn函数
//------------------------------------------
//call和apply
let obj = {name:'obj'}
function fn1(){console.log(this);}
fn1.call(obj); //obj
let fn2 = () => {console.log(this);}
fn2.call(obj); //window
function fn3(){console.log(this);}
fn3.apply(obj); //obj
let fn4 = () => {console.log(this);}
fn4.apply(obj); //window
注意:上面的代码有些在延时函数里,有些不在,所以打印的顺序可能不同
3.箭头函数中没有arguments(类数组),只能基于…arg获取传递的参数集合(数组)
//1.
let a = function(){
console.log(arguments);
}
a(10,20,30);//Arguments(3) [10, 20, 30, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//2.
let b = () => {
console.log(arguments);
};
b(10,20,30);//报错:arguments is not defined
//3.
let c = function(...arg){console.log(arg);}
c(10,20,30);//[10, 20, 30]
//4.
let d = (...arg) => {console.log(arg);}
d(10,20,30);//[10, 20, 30]
4.箭头函数不能被new执行(因为:箭头函数没有自己的this也没有prototype)
//普通函数:
function fn1(){
this.name = 'fn1';
console.log(this.name + ' --- new了');
}
console.log(fn1.prototype); //{constructor: ƒ}
let f1 = new fn1(); //fn1 --- new了
//箭头函数:
let fn2 = () => {
this.name = 'fn2';
console.log(this.name + ' --- new了');
}
console.log(fn2.prototype); //undefined
let f2 = new fn2(); //报错,fn2 is not a constructor ---- fn2不是一个构造器*/