获取函数调用者的范围 [英] Getting scope of function caller

查看:95
本文介绍了获取函数调用者的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var createDelayed = function(h,o,scope)

我有一个功能在ExtJS的第1433行中断){
console.log(arguments); //日志未定义全部。
return function(){
var args = Array.prototype.slice.call(arguments,0);
setTimeout(function(){
h.apply(scope,args);
},o.delay || 10);
};
};

有没有办法看到从内部执行一个函数的行? >

(因为它是第三方lib,我不能真正做到

  var我=这个; 

和日志

解决方案

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



没有办法得到原始函数的范围,没有传递它。在以下示例中,您不能确定 foo 中的 值(除了知道 this here):

  function foo(){
bar ();
}

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

foo();

文档






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

  function foo(){
bar();
}

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

foo();

对于小提琴,它在Chrome中记录类似于以下内容,其中行尾说行号和字符位置:

 错误
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


I have a function that breaks somewhere in Line 1433 of ExtJS.

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)

解决方案

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.

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):

function foo() {
    bar();
}

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

foo();

Documentation


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/.

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:

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

这篇关于获取函数调用者的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆