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)
函数名返回''
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)
因此,获取箭头函数名称的唯一方法是访问对其的直接引用。
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)
| 归档时间: |
|
| 查看次数: |
2835 次 |
| 最近记录: |