简体   繁体   English

jQuery + 获取函数名

[英]jQuery + access to the name of the function

I now is a silly question but is this, I can give the name of the current function?我现在是一个愚蠢的问题,但这是,我可以给出当前函数的名称吗? I am really interested in this because I usually use the console and i want to get it我对这个真的很感兴趣,因为我通常使用控制台,我想得到它

var debug = true;
var myFunction = $( "div" ).on( "click", function(e) {
    //
    var error = "";
    var something = true;
    //
    if(something == true) error = "Something has happened"; 
    if(debug)
        console.log("Ups!" + myFunction.name + " >> "+ error);
    //
});

Thanks in advance提前致谢

This doesn't work in my jQuery example这在我的 jQuery 示例中不起作用

Can I get the name of the currently running function in JavaScript? 我可以在 JavaScript 中获取当前正在运行的函数的名称吗?

You will need to use a named function instead of anonymous, ie give it a name:您将需要使用命名函数而不是匿名函数,即为其命名:

$( "div" ).on( "click", function myFunction(e) {
    console.log("Ups!" + myFunction.name);
});

Also, you need to understand that with the code此外,您需要了解代码

var something = $("div").on("click", function() {})

something will be an instance of jQuery, not a callback function of course. something将是 jQuery 的一个实例,当然不是回调函数。 So once again: use named function.所以再次:使用命名函数。

arguments.callee.toString();

will get you the entire callee line of code (ie function MyFunction() ) then just substring it out from there.将为您提供整个被调用者的代码行(即函数 MyFunction() ),然后从那里将其子串出来。

Update for your exact situation, try更新您的确切情况,请尝试

(function() {console.log("Ups!" + arguments.callee.toString() + " error");})();

sometimes declaring the action as an inline function makes things tick a little better.有时将操作声明为内联函数会使事情变得更好一些。

You can get the function name using arguments.callee or arguments.callee.name .您可以使用arguments.calleearguments.callee.name获取函数名称。

  • arguments.callee returns the name with a brackets ( myFunction() ). arguments.callee返回带括号的名称 ( myFunction() )。
  • arguments.callee.name returns the name without those brackets ( myFunction ). arguments.callee.name返回没有这些括号的名称 ( myFunction )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM