javascript 获取函数调用者的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7444399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting scope of function caller
提问by Alex
I have a function that breaks somewhere in Line 1433 of ExtJS.
我有一个函数在 ExtJS 的第 1433 行某处中断。
var createDelayed = function(h, o, scope){
console.log(arguments); //logs undefined all round.
return function(){
var args = Array.prototype.slice.call(arguments, 0);
setTimeout(function(){
h.apply(scope, args);
}, o.delay || 10);
};
};
Is there any way to see what line a function is executed from, from within itself?
有什么办法可以从内部查看函数是从哪一行执行的?
(since it's a third party lib, and I cant really do
(因为它是第三方库,我真的做不到
var me =this;
and log me
)
并记录me
)
回答by pimvdb
There is arguments.callee.caller
, which refers to the function that called the function in which you access that property. arguments.callee
is the function itself.
有arguments.callee.caller
,它指的是调用您访问该属性的函数的函数。arguments.callee
是函数本身。
There is no way to get the scope of the original function without passing it. In the following example, you cannot determine the this
value inside foo
(apart from knowing there is nothing special happening with this
here):
没有传递它就没有办法获得原始函数的作用域。在下面的例子中,你不能确定this
里面的值foo
(除了知道这里没有什么特别的事情发生this
):
function foo() {
bar();
}
function bar() {
console.log(arguments.callee); // bar function
console.log(arguments.callee.caller); // foo function
}
foo();
To get the line number things becomes trickier, but you can throw an error and look at the stack trace: http://jsfiddle.net/pimvdb/6C47r/.
要获取行号,事情变得更加棘手,但您可以抛出错误并查看堆栈跟踪:http: //jsfiddle.net/pimvdb/6C47r/。
function foo() {
bar();
}
function bar() {
try { throw new Error; }
catch(e) {
console.log(e.stack);
}
}
foo();
For the fiddle, it logs something similar to the following in Chrome, where the end of the line says the line number and character position:
对于小提琴,它会在 Chrome 中记录类似于以下内容的内容,其中行尾表示行号和字符位置:
Error
at bar (http://fiddle.jshell.net/pimvdb/6C47r/show/:23:17)
at foo (http://fiddle.jshell.net/pimvdb/6C47r/show/:19:5)
at http://fiddle.jshell.net/pimvdb/6C47r/show/:29:1