JavaScript Caller Information
In JavaScript, it is possible to obtain details about the function calling another function.
Caller Function Name
You have already mentioned the approach for retrieving the caller function name:
var callerFunc = arguments.callee.caller.toString(); callerFuncName = (callerFunc.substring(callerFunc.indexOf("function") + 8, callerFunc.indexOf("(")) || "anoynmous")
Caller Line Number
To extract the line number from which the method was called, you can utilize the Error object:
function getErrorObject(){ try { throw Error('') } catch(err) { return err; } } var err = getErrorObject(); var caller_line = err.stack.split("\n")[4]; var index = caller_line.indexOf("at "); var clean = caller_line.slice(index+2, caller_line.length);
In this code, the getErrorObject function generates an error object. By accessing the stack property, you can retrieve a stack trace, which contains information about the current calling context.
Caller File Source URL
Unfortunately, directly obtaining the JavaScript file source URL from which the method was called is not possible in most JavaScript implementations.
The above is the detailed content of How Can I Retrieve Information About JavaScript Caller Functions?. For more information, please follow other related articles on the PHP Chinese website!