最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How to get function name in javascript arrow function? - Stack Overflow

programmeradmin5浏览0评论

I want to get a function's name in an arrow function

Actually, if we write

function abc(){
  let funcName = arguments.callee.name
}

But in an arrow function

abc: ()=>{
  let funcName = arguments.callee.name
}

funcName return ''

I want to get a function's name in an arrow function

Actually, if we write

function abc(){
  let funcName = arguments.callee.name
}

But in an arrow function

abc: ()=>{
  let funcName = arguments.callee.name
}

funcName return ''

Share Improve this question edited Aug 17, 2021 at 4:37 Saiyavong MITTHASONE asked Aug 17, 2021 at 4:33 Saiyavong MITTHASONESaiyavong MITTHASONE 1111 silver badge9 bronze badges 7
  • Isn't it an anonymous function ? – MaxZoom Commented Aug 17, 2021 at 4:34
  • 2 This is kind of like asking what is the variable name of the number 12 – slebetman Commented Aug 17, 2021 at 4:37
  • @MaxZoom I have added function name – Saiyavong MITTHASONE Commented Aug 17, 2021 at 4:37
  • 1 Are you sure you don't get an error when you access arguments object inside the arrow function? – Yousaf Commented Aug 17, 2021 at 4:45
  • 1 The name of the function is "abc:", assigned to the arrow function when it was piled as the abc property of a parent object. You could just hard code it in the arrow function if you want. – traktor Commented Aug 17, 2021 at 6:06
 |  Show 2 more ments

1 Answer 1

Reset to default 8
  • Arrow functions do not have an arguments binding. But they have access to the arguments object of the closest non-arrow parent function. Named and rest parameters are heavily relied upon to capture the arguments passed to arrow functions.
function dummy() {
  return (() => arguments.callee.name)(); // dummy
}
  • The value of this inside an arrow function remains the same throughout the lifecycle of the function and is bound to the value of the closest this-providing environment.
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
  • Arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword. As such, a prototype property does not exist for an arrow function.

Therefor, the only way to get the name of an arrow function is from accessing the direct reference to it.

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

const obj = {
  a: () => obj.a.name;
}
console.log(obj.a()); // "a"
发布评论

评论列表(0)

  1. 暂无评论