箭頭函數(shù)的定義
箭頭函數(shù)是匿名函數(shù),不能作為構(gòu)造函數(shù),它使表達(dá)更加簡(jiǎn)潔槽华,簡(jiǎn)化了回調(diào)函數(shù)
箭頭函數(shù)最重要的:this指向問(wèn)題
- 箭頭函數(shù)的this指向的是父級(jí)作用域中的this,是通過(guò)查找作用域鏈來(lái)確定this的值趟妥,指向的是定義它的對(duì)象猫态,而不是使用時(shí)所在的對(duì)象。
//普通函數(shù)中披摄,this總是指向調(diào)用它的對(duì)象亲雪,如果用作構(gòu)造函數(shù),this指向創(chuàng)建的對(duì)象實(shí)例
let obj1 = {
a:function(){
console.log(this)
}
b:()=>{
console.log(this)
}
}
obj.a()//this指向obj
obj.b()//this指向window
let obj2 = {
fun:function(){
return ()=>{
console.log(this)
}
}
}
//箭頭函數(shù)的this指向定義的時(shí)候疚膊、外層第一個(gè)普通函數(shù)的this
//這里箭頭函數(shù)指向的是 fun函數(shù)义辕,fun函數(shù)指向的是obj2,所以這里this會(huì)指向obj2
obj2.fun()() //this指向obj2
- 箭頭函數(shù)中的this只在箭頭函數(shù)定義時(shí)就決定的寓盗,而且不能修改(call(),apply(),bind())
let obj1 = {
a:function(){
console.log(this)
}
b:()=>{
console.log(this)
}
}
obj.a()//this指向obj
obj.b()//this指向window
obj.b().call(obj) //this還是會(huì)指向window灌砖,指向不能被修改
箭頭函數(shù)不能當(dāng)做構(gòu)造函數(shù)(不能被new)
不能被當(dāng)做構(gòu)造函數(shù)使用,通過(guò)new命令來(lái)作為構(gòu)造函數(shù)會(huì)報(bào)錯(cuò)傀蚌,不存在prototypepe屬性基显。
let fun = ()=>{
return 123
}
console.log(new fun()) //會(huì)報(bào)錯(cuò)
console.log(run.prototype)//undefined
箭頭函數(shù)沒(méi)有arguments對(duì)象
每個(gè)普通函數(shù)調(diào)用后都具有一個(gè)arguments對(duì)象,用來(lái)存儲(chǔ)實(shí)際傳遞的參數(shù)善炫。但是箭頭函數(shù)沒(méi)有此對(duì)象
function f1(arr) {
console.log(arguments);
}
f1([1,2,3]); // [1,2,3]
let f2 = (arr) => {
console.log(arguments);
}
f2([1,3,9]); //Uncaught ReferenceError: arguments is not defined
總結(jié):
- 1.箭頭函數(shù)this指向外層第一個(gè)普通函數(shù)this的指向撩幽,且不能修改指向,如call()销部,bind()摸航,apply()。
- 2.普通函數(shù)的this指向調(diào)用它的那個(gè)對(duì)象舅桩,誰(shuí)調(diào)用指向誰(shuí)酱虎。