Is it possible to get the caller context in javascript?

Since this keyword referes to ThisBinding in a LexicalEnvironment, and javascript (or ECMAScript) doesn't allow programmatic access to LexicalEnvironment (in fact, no programmatic access to the whole Execution Context), so it is impossible to get the context of caller.

Also, when you try test.demo() in a global context, there should be no caller at all, neither an attached context to the caller, this is just a Global Code, not a calling context.


By context, I assume you mean this? That depends on how the function is invoked, not from where it is invoked.

For example (using a Webkit console):

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"

Incidentally, arguments.caller is deprecated.


The value of a function's this keyword is set by the call, it isn't "context". Functions have an execution context, which includes its this value. It is not defined by this.

In any case, since all functions have a this variable that is a property of its variable object, you can't reference any other this keyword in scope unless it's passed to the function. You can't directly access the variable object; you are dependent on variable resolution on the scope chain so this will always be the current execution context's this.