ES6 箭头函数和普通函数究竟什么区别

面试中少不了面试官问箭头函数的 this 有何特殊。我们知道虽然 babel 转义后是在外层定义 _this 指向了外层的 this ,然后在传给内层的函数来解决这个事情的

function index() {
  let func = () => { console.log(this) }
}

// 根据 babel 官网 https://babel.docschina.org/repl 在线转译成
"use strict";

function index() {
  var _this = this;

  var func = function func() {
    console.log(_this);
  };
}

但原生的 ES6 的箭头函数可不是这样。且看 MDN 的描述:

箭头函数表达式的语法比函数表达式更简洁,并且没有自己的this,arguments,super或new.target。箭头函数表达式更适用于那些本来需要匿名函数的地方,并且它不能用作构造函数。

总结一下,箭头函数有坑。它并没有 this,就只是在函数执行时,取外部的作用域的 this

然后注意以下陷阱:箭头函数能 new 吗?若是被 babel 转译成了普通函数,new 调用却是没问题;但原生的不能,因为它没有 prototype 属性,new 操作符总需要作用 prototype 的,所以它不能用作构造函数。

var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor

箭头函数没有 prototype 属性

var Foo = () => {};
console.log(Foo.prototype); // undefined

箭头函数没有 argument

var func = () => { console.log(arguments) }
func(1) // Uncaught ReferenceError: arguments is not defined

// 多数情况可以使用剩余参数改写
var func = (...args) => { console.log(args) }
func(1) // [1]

参考

MDN-Arrow_functions

posted @ 2020-04-01 00:20  Ever-Lose  阅读(267)  评论(0编辑  收藏  举报