有可能这样做吗:
myfile.js:
function foo() {
alert(<my-function-name>);
// pops-up "foo"
// or even better: "myfile.js : foo"
}
我的堆栈中有Dojo和jQuery框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。
有可能这样做吗:
myfile.js:
function foo() {
alert(<my-function-name>);
// pops-up "foo"
// or even better: "myfile.js : foo"
}
我的堆栈中有Dojo和jQuery框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。
当前回答
这个问题的最新答案可以在这个答案中找到: https://stackoverflow.com/a/2161470/632495
如果你不想点击:
function test() {
var z = arguments.callee.name;
console.log(z);
}
其他回答
这应该做到:
var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);
对于调用者,只需使用caller. tostring()。
对于非匿名函数
function foo()
{
alert(arguments.callee.name)
}
但在错误处理程序的情况下结果应该是错误处理程序函数的名称,不是吗?
这里有一个可行的方法:
export function getFunctionCallerName (){
// gets the text between whitespace for second part of stacktrace
return (new Error()).stack.match(/at (\S+)/g)[1].slice(3);
}
然后在你们的测试中
import { expect } from 'chai';
import { getFunctionCallerName } from '../../../lib/util/functions';
describe('Testing caller name', () => {
it('should return the name of the function', () => {
function getThisName(){
return getFunctionCallerName();
}
const functionName = getThisName();
expect(functionName).to.equal('getThisName');
});
it('should work with an anonymous function', () => {
const anonymousFn = function (){
return getFunctionCallerName();
};
const functionName = anonymousFn();
expect(functionName).to.equal('anonymousFn');
});
it('should work with an anonymous function', () => {
const fnName = (function (){
return getFunctionCallerName();
})();
expect(/\/util\/functions\.js/.test(fnName)).to.eql(true);
});
});
注意,只有当测试位于/util/functions中时,第三个测试才会工作
下面代码段中的getMyName函数返回调用函数的名称。这是一个黑客,依赖于非标准的特性:Error.prototype.stack。注意,由Error.prototype.stack返回的字符串格式在不同的引擎中实现是不同的,所以这可能不会在任何地方都适用:
函数getMyName() { var e = new错误('dummy'); Var stack = e.stack .split(“\ n”)[2] // " at functionName(…)"“= >”functionName .replace (/ ^ \ s + \ s + (+ ?) \ s。+/g, '$1'); 返回栈 } 函数foo () { 返回getMyName () } 功能栏(){ 返回foo () } console.log (bar ())
关于其他解决方案:争论。严格模式下不允许使用callee,严格模式下不允许使用Function.prototype.calleris非标准的。
在ES5及以上版本中,无法访问该信息。
在旧版本的JS中,你可以使用arguments.callee来获取它。
不过,您可能需要解析这个名称,因为它可能包含一些额外的垃圾。不过,在某些实现中,您可以使用arguments.callee.name简单地获取名称。
解析:
function DisplayMyName()
{
var myName = arguments.callee.toString();
myName = myName.substr('function '.length);
myName = myName.substr(0, myName.indexOf('('));
alert(myName);
}
获取当前函数名。