撤底理解es6中的箭頭函數(shù)

本質(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容