Determine calling function in javascript [duplicate]

梦想与她 提交于 2019-11-28 08:50:25

Each function has a caller property defined.

From https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/caller:

function myFunc() {
    if (myFunc.caller == null) {
        return ("The function was called from the top!");
    } else
        return ("This function's caller was " + myFunc.caller);
    }
}

The Function.caller property is not part of the ECMA3 standard but it's implemented across all major browsers, including IE and Firefox.

If you're using an anonymous function, you can still access the caller property via the arguments.calee property:

function() {
    if (arguments.callee.caller == null) {
        return ("The function was called from the top!");
    } else
        return ("This function's caller was " + arguments.callee.caller);
    }
}

Note that this code is accessing the current function, and then referencing the same non-standard caller property on it. This is distinct from using the deprecated arguments.caller property directly, which is not implemented in some modern browsers.

In chromeos on cr-48, arguments.callee.caller gives the whole function body as a string, for both named anonymous caller functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!