I am trying to execute a function at a different scope than where it is defined. I need to get the variables available in the runtime scope available to the functions context.
A sample code can be like
var k = function () { alert(x); };
(function () {
var x = 100;
k();
})();
Its not possible for function k to access x which is in the scope where it is run.
Possible work arounds that I have are:
- inject x as a parameter to function
use eval like
var k = "function () { alert(x); }"; (function () { var x = 100; var m = eval("("+k+")");//prints 100 m(); })(); //But this same work around wont work if I use k = "alert(x);" and //define m = new Function(k);
bind x as the
this
context for the function and doalert(this)
.
If i rule out the above 3 options, are there any other ways of approaching this problem?
Is there a way I can inject variables into a function scope in runtime, just like call
,apply
and bind
does for this
?