Is it possible to get the caller context in javascript?

Javascript

Javascript Problem Overview


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

I tried arguments.callee and arguments.callee.caller,and no luck...

Javascript Solutions


Solution 1 - 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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnew_perlView Question on Stackoverflow
Solution 1 - JavascriptotakustayView Answer on Stackoverflow
Solution 2 - JavascriptSethView Answer on Stackoverflow
Solution 3 - JavascriptRobGView Answer on Stackoverflow