简体   繁体   English

调用函数名称时如何获取?

[英]How can I get a function name when it is being called?

I'm not sure if this is a good idea or not, but I'd like to be able to get the name of a function from within it, while it is being called. 我不确定这是否是个好主意,但是我希望能够在调用函数时从函数中获取函数的名称。 The test code I wrote below seems to work, in that it doesn't cause a name clash, but I can't get the name of the function without knowing it first. 我在下面编写的测试代码似乎可以正常工作,因为它不会引起名称冲突,但是在不先了解函数的情况下我无法获得该函数的名称。

function And(){
    return "test";
};
var X = {
    And:  function And(){
        return this.And.name;
    }
};
document.write(X.And());

Is there any way of achieving this that doesn't involve binding the context (ie the value of 'this') on the function? 有什么方法可以实现,而无需在函数上绑定上下文(即“ this”的值)?

Simply by using this aguments.callee.name; 只需使用此aguments.callee.name;

try this example : 试试这个例子:

function myFunc() 
{ 
    return arguments.callee.name; 
}

Note that the arguments.callee will be depricated 请注意arguments.callee将被描述

Function.caller or arguments.callee.name Function.caller或arguments.callee.name

However arguments.callee() doesn't work under ES5. 但是arguments.callee()在ES5下不起作用。 And Function.caller is not standard. 而且Function.caller不是标准的。

暂无
暂无

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

相关问题 如何在不立即调用此函数的情况下将其添加到数组? - How can I add this function to an array without it being called immediately? 如何确保我的函数被调用并正在运行 - How can I ensure that my function is being called and running 如何判断某个地方是否正在调用JS函数? - How can I tell if a JS function is being called somewhere? 返回页面时未调用函数 - Function not being called when I return to the page 当使用 React 测试库更改数据属性时,如何编写一个测试用例来验证 function 是否被正确调用? - How can I write a test case that verifies that the function is being called correctly when the data prop changes using React Testing Library? 什么时候以及如何在JavaScript中调用此函数? - When and how is this function being called in JavaScript? 当使用递归方法调用 function 时,我无法理解如何从数组中获取某个值 - Can't understand how I get a certain value from an array when a function is called using recursive method 如何获得函数名称? - How can I get the name of a function? 如何在事件处理程序中包含一个函数(及其参数),而无需在页面加载时调用该函数? - How can I include a function (and its parameter) within an event handler, without the function being called on page load? 如何防止某个函数在Javascript的另一个函数之外被调用? - How can I prevent a function from being called outside another function in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM