本質(zhì)上
- 是一個(gè)函數(shù),是function
- 是一個(gè)被編譯層加工過(guò)的函數(shù)
- 用 babel 編譯一下箭頭函數(shù)看看,如下
//es6
const a = ()=>{ console.log(this) };
const b = ()=>{ console.log(arguments) }
function aaa(){
const c = ()=>{ console.log(this) };
c();
}
aaa();
function bbb(){
const c = ()=>{ console.log(arguments) };
c();
}
bbb()
//編譯后
var a = function a() {
console.log(undefined);
};
var _arguments = arguments;
var b = function b() {
console.log(_arguments);
};
function aaa() {
var _this = this;
var c = function c() {
console.log(_this);
};
c();
}
aaa();
function bbb() {
var _arguments2 = arguments;
var c = function c() {
console.log(_arguments2);
};
c();
}
bbb();
特性解密
- 內(nèi)部沒(méi)有 this,也沒(méi)有 arguments
==this==
- 單獨(dú)調(diào)用時(shí),內(nèi)部沒(méi)有 this,因?yàn)樵诰幾g時(shí)被替換成了 undefined
- 但是,如果其外層存在 this(一個(gè)普通函數(shù)),那么編譯時(shí)會(huì)將外層的 this 傳入箭頭函數(shù)內(nèi)部,使其“具有了” this
==arguments==
- 其內(nèi)部的 arguments 和 this 的表現(xiàn)略有不同。不管是否單獨(dú)調(diào)用箭頭函數(shù),arguments 都來(lái)自于外部傳入,使其“具有了” arguments
==柯里化==
- 實(shí)際上這種調(diào)用方式,就是柯里化一個(gè)函數(shù)的一種實(shí)現(xiàn)方式(或者語(yǔ)法糖)
//es6
const sum = num1 => num2 => num3 => num1 + num2 + num3;
//編譯后
var sum = function sum(num1) {
return function (num2) {
return function (num3) {
return num1 + num2 + num3;
};
};
};
不適合用箭頭函數(shù)的情形
- 在對(duì)象上定義函數(shù)
- 在原型上定義函數(shù)
- 動(dòng)態(tài)上下文中的回調(diào)函數(shù),比如 dom 點(diǎn)擊事件回調(diào)
- 太過(guò)復(fù)雜的函數(shù)
相關(guān)文章
箭頭函數(shù)沒(méi)有綁定this