如何获取javascript箭头函数中的函数名称?

Sai*_*ONE 7 javascript node.js ecmascript-6

我想在箭头函数中获取函数的名称

事实上,如果我们写

function abc(){
  let funcName = arguments.callee.name
}
Run Code Online (Sandbox Code Playgroud)

但在箭头函数中

abc: ()=>{
  let funcName = arguments.callee.name
}
Run Code Online (Sandbox Code Playgroud)

函数名返回''

Chr*_*her 8

  • 箭头函数没有arguments绑定。但它们可以访问最接近的非箭头父函数的参数对象。命名参数和剩余参数严重依赖于捕获传递给箭头函数的参数。
function dummy() {
  return (() => arguments.callee.name)(); // dummy
}
Run Code Online (Sandbox Code Playgroud)
  • 箭头函数内部的值this在函数的整个生命周期中保持不变,并且绑定到最接近的this提供环境的值。
const obj = {
  // like a normal function, returns obj - defines like obj.a = function a() {};
  a() { return this },
  // arrow function uses global as this
  b: () => { return this },
};
console.log(obj.a() == obj) // true
console.log(obj.b() == obj) // false
console.log(obj.b() == window) // true
Run Code Online (Sandbox Code Playgroud)
  • 箭头函数永远不能用作构造函数。因此,永远不能使用 new 关键字调用它们。因此,箭头函数不存在原型属性。

因此,获取箭头函数名称的唯一方法是访问对其的直接引用。

const arrow = () => arrow.name;
console.log(arrow()); // "arrow"

const obj = {
  a: () => obj.a.name;
}
console.log(obj.a()); // "a"
Run Code Online (Sandbox Code Playgroud)

  • *“总是绑定到最近的非箭头父函数中的`this`的值。”*对于大多数用例来说可能足够好,但只是为了完整性:它是最接近的“提供this”环境,可以是全局环境或模块环境(并不是说那些“this”值会非常有趣,但仍然如此)。 (2认同)