3

Is it possible to run a function in another context where it can access local variables with this context?

I made this proof of concept:

var t = (function()
{
    "use strict";
    var ab = 5;

    var f = (function(t)
    {
        return function(c){ c.call(t); }
    })(t);

    return f;

})();

t(function()
{
    return ab;
});

This give me this error: ReferenceError: ab is not defined

Is there a way that the anonymous function that I pass to t can access the local variable ab?

1
  • Imagine debugging that? Commented May 19, 2014 at 13:06

1 Answer 1

2

Unfortunately (or fortunately) you can't do that. The problem which arises here is that you cannot "pass around" the such called Activation Object from a function (context). Function.prototype.apply and .call can only provide an option to set the context for a function from any regular Javascript Object, but formal parameter, function declarations and variables are not stored in any "regular" object. These values are hold in the Scope chain underneath and are stored in the such called Activation Object (or Lexical Environment Record) which you cannot access directly from Javascript.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the declaration. It is very useful. Then, there aren't a form to access a "var" in another context with "call" method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.