有可能这样做吗:
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框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。
当前回答
这里有一句话:
arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '')
是这样的:
function logChanges() {
let whoami = arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '');
console.log(whoami + ': just getting started.');
}
其他回答
这是我在这里看到的一些回应的组合。(在FF, Chrome, IE11测试)
function functionName()
{
var myName = functionName.caller.toString();
myName = myName.substr('function '.length);
myName = myName.substr(0, myName.indexOf('('));
return myName;
}
function randomFunction(){
var proof = "This proves that I found the name '" + functionName() + "'";
alert(proof);
}
调用randomFunction()将提醒包含函数名的字符串。
JS小提琴演示:http://jsfiddle.net/mjgqfhbe/
答案很简单:alert(arguments.callee.name);
(function f() {
console.log(f.name); //logs f
})();
打印稿变化:
function f1() {}
function f2(f:Function) {
console.log(f.name);
}
f2(f1); //Logs f1
注意仅适用于ES6/ES2015兼容引擎。更多信息请参见
这里有一个可行的方法:
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中时,第三个测试才会工作
这个问题的最新答案可以在这个答案中找到: https://stackoverflow.com/a/2161470/632495
如果你不想点击:
function test() {
var z = arguments.callee.name;
console.log(z);
}