首页 > 其他 > 详细

ES6 箭头函数的陷阱

时间:2020-04-01 10:26:43      阅读:70      评论:0      收藏:0      [点我收藏+]

面试中少不了面试官问箭头函数的 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 调用却是没问题;但原生的不能,它不能用作构造函数。

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

ES6 箭头函数的陷阱

原文:https://www.cnblogs.com/everlose/p/12609834.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!