If you execute the following code:
this.TestClass.call("this");
and in the TestCalss:
console.log(eval(pString));
You will notice that it logs the window
object. The string this
does not retain its context. If you had logged window.arrTest1
, you would have obtained the desired outcome.
So...
You should pass the context:
this.TestClass.Run.call(this, "this.arrTest1 = [1]");
And in your TestCalss
TestClass = {
Run : (pString) => {
return eval(pString)
}
};
Why does eval.call(this, pString) not work?
There is a distinction in how eval()
operates. eval()
is not a conventional javascript function. As explained here: How override eval function in javascript?
As you may have already attempted, something like this:
(0, eval)(pString); // this is an indirect call to eval
What constitutes an indirect call??
According to ES5, all of these are indirect calls and should execute code in global scope
The global scope in your scenario will be null, since typescript does not inherently provide a global scope. (To the best of my knowledge)
For a detailed explanation about eval
, please refer to:
In accordance with the above resource, the following are examples of indirect eval
calls :
(1, eval)('...')
(eval, eval)('...')
(1 ? eval : 0)('...')
(__ = eval)('...')
var e = eval; e('...')
(function(e) { e('...') })(eval)
(function(e) { return e })(eval)('...')
(function() { arguments[0]('...') })(eval)
this.eval('...')
this['eval']('...')
[eval][0]('...')
eval.call(this, '...') <-- This is your case.
eval('eval')('...')
Another passage from the article:
Not understanding what’s going on, some people unfortunately come up with rather monstrous solutions like eval.call(window, '...'), window.eval.call(window, '...') and even scarier combinations. All of those are, once again, nothing but indirect eval calls.
There's also a very insightful section explaining why (0, eval)(pString)
is considered an indirect call. Please review this. Unfortunately, I could not find a solid justification for why eval.call(this, '...')
is seen as indirect. Perhaps we just need to accept the notion that eval()
is not a traditional function.