是否有可能在javascript中获取调用者上下文?

时间:2012-03-13 05:57:19

标签: javascript

var test = {
    demo: function(){
      //get the caller context here
    }
}
//when this gets called, the caller context should be window.
test.demo();

我尝试了arguments.calleearguments.callee.caller,但没有运气......

3 个答案:

答案 0 :(得分:42)

由于this关键字在ThisBinding中引用LexicalEnvironment,而javascript(或ECMAScript)不允许以编程方式访问LexicalEnvironment(事实上,没有编程访问权限)对整个Execution Context),所以不可能来获取调用者的上下文。

此外,当您在全局环境中尝试test.demo()时,应该没有来电者上下文也不应该来电者 ,这只是全局代码,而不是调用上下文。

答案 1 :(得分:8)

根据上下文,我认为你的意思是this?这取决于函数的调用方式,而不是调用函数的位置。

例如(使用Webkit控制台):

var test = {
    demo: function() {
        console.log(this);
    }
}
test.demo();    // logs the "test" object
var test2 = test.demo;
test2();        // logs "DOMWindow"
test.demo.apply("Cheese"); // logs "String"

顺便说一句,arguments.caller已被弃用。

答案 2 :(得分:5)

函数的this关键字的值由调用设置,它不是“上下文”。函数具有执行上下文,其中包含 this 值。它不是由this定义的。

在任何情况下,由于所有函数都有一个this变量,该变量是其变量对象的属性,因此除非将其传递给函数,否则不能在范围中引用任何其他this关键字。您无法直接访问变量对象;您依赖于范围链上的变量分辨率,因此this将始终是当前执行上下文的this

相关问题