获取函数调用者的范围

时间:2011-09-16 12:04:53

标签: javascript 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);
    };
};

有没有办法从内部查看函数的执行行?

(因为它是第三方lib,我真的不能

var me =this;

并记录me

1 个答案:

答案 0 :(得分:11)

arguments.callee.caller,它指的是调用访问该属性的函数的函数。 arguments.callee是函数本身。

没有传递它就无法获得原始函数的范围。在以下示例中,您无法确定this内的foo值(除了知道此处this没有发生任何特殊情况):

function foo() {
    bar();
}

function bar() {
    console.log(arguments.callee);        // bar function
    console.log(arguments.callee.caller); // foo function
}

foo();

Documentation


要获取行号,事情变得更加棘手,但您可以抛出错误并查看堆栈跟踪:http://jsfiddle.net/pimvdb/6C47r/

function foo() {
    bar();
}

function bar() {
    try { throw new Error; }
    catch(e) {
        console.log(e.stack);
    }
}

foo();

对于小提琴,它在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