撤底理解es6中的箭头函数

本质上

  • 是一个函数,是function
  • 是一个被编译层加工过的函数
  • 用 babel 编译一下箭头函数看看,如下
//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();

特性解密

  • 内部没有 this,也没有 arguments

==this==

  • 单独调用时,内部没有 this,因为在编译时被替换成了 undefined
  • 但是,如果其外层存在 this(一个普通函数),那么编译时会将外层的 this 传入箭头函数内部,使其“具有了” this

==arguments==

  • 其内部的 arguments 和 this 的表现略有不同。不管是否单独调用箭头函数,arguments 都来自于外部传入,使其“具有了” arguments

==柯里化==

  • 实际上这种调用方式,就是柯里化一个函数的一种实现方式(或者语法糖)
//es6
const sum = num1 => num2 => num3 => num1 + num2 + num3;
//编译后
var sum = function sum(num1) {
  return function (num2) {
    return function (num3) {
      return num1 + num2 + num3;
    };
  };
};

不适合用箭头函数的情形

  • 在对象上定义函数
  • 在原型上定义函数
  • 动态上下文中的回调函数,比如 dom 点击事件回调
  • 太过复杂的函数

相关文章
箭头函数没有绑定this

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。