在严格模式或ES6中,如何在函数内部拿到函数对象本身?

更新日期: 2018-01-15阅读: 5.4k标签: 严格模式

函数中方法函数对象本身,我们以前可以这样实现:

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();



链接: https://www.fly63.com/article/detial/358

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!