function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
有办法找到调用堆栈吗?
function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
有办法找到调用堆栈吗?
当前回答
试试下面的代码:
function getStackTrace(){
var f = arguments.callee;
var ret = [];
var item = {};
var iter = 0;
while ( f = f.caller ){
// Initialize
item = {
name: f.name || null,
args: [], // Empty array = no arguments passed
callback: f
};
// Function arguments
if ( f.arguments ){
for ( iter = 0; iter<f.arguments.length; iter++ ){
item.args[iter] = f.arguments[iter];
}
} else {
item.args = null; // null = argument listing not supported
}
ret.push( item );
}
return ret;
}
在火狐21和Chromium-25里为我工作过。
其他回答
function Hello() {
alert(Hello.caller);
}
试着访问这个:
arguments.callee.caller.name
解决这个问题的另一种方法是简单地将调用函数的名称作为参数传递。
例如:
function reformatString(string, callerName) {
if (callerName === "uid") {
string = string.toUpperCase();
}
return string;
}
现在,你可以这样调用这个函数:
function uid(){
var myString = "apples";
reformatString(myString, function.name);
}
我的示例使用了对函数名的硬编码检查,但是您可以轻松地使用switch语句或其他逻辑来完成您想要的操作。
使用*arguments.callee更安全。调用自参数。不赞成调用…
据我所知,我们有两种方法从给定的资源中得到
arguments.caller whoCalled()函数 { 如果参数。Caller == null) console.log('我是从全局作用域调用的。'); 其他的 console.log(参数。Caller + '打电话给我!'); } Function.caller myFunc()函数 { 如果(myFunc。调用者== null) { 返回'函数是从顶部调用的!'; } 其他的 { 返回'这个函数的调用者是' + myfuncc .caller; } }
我想你已经有答案了:)。