在严格模式或ES6中,如何在函数内部拿到函数对象本身?
在函数中方法函数对象本身,我们以前可以这样实现:
function fn(){
console.log(fn.name);
console.log(arguments.callee.name);
}
fn();但是在严格模式或ES6下,使用callee/caller会报错,如下:
'use strict';
function fn(){
console.log(arguments.callee.name);
}
fn();
//Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them由于不能使用arguments.callee,在不使用函数名本身的情况,有什么方法可以实现呢?这里写个 hack 的解决方法:
'use strict'
function jamie(){
var callerName;
try {
throw new Error();
}catch(e){
var re = /(\w+)@|at (\w+) \(/g, st = e.stack, m;
re.exec(st), m = re.exec(st);
callerName = m[1] || m[2];
}
console.log(callerName);
};
function fn (){
jamie();
}
fn();本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!