在严格模式或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();本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!