3 ms·
so the comma operator doesn't do anything special other than return the last value - so why not just call eval directly? If somebody rebound eval to redefine t
by chii 8y ago
so the comma operator doesn't do anything special other than return the last value - so why not just call eval directly?
If somebody rebound eval to redefine the 'this' inside - e.g., eval = (function(){myThis = ... ; return function(a){eval.apply(mythis, [a]);};})();
then calling eval with (0, eval)('this') will still not have rebinded the 'this' inside eval right? So why not just directly call eval('this')? Or am i missing the point?
- Klathmon 8y agoIt's getting to the limit of my knowledge here, so please don't take this as fact, however: I believe it is because of a weird distinction between "direct" and "indirect" calls in javascript. The spec says that an indirect call is guaranteed to execute in the global context, but a direct call will execute in whatever context it's in. The `(0, eval)` makes it an indirect call by evaluating an expression that returns the function. I'm not quite sure about the details of why indirect calls are treated that way though...
- mratzloff 8y agoI believe it is because of a weird distinction between "direct" and "indirect" calls in javascript. The spec says that an indirect call is guaranteed to execute in the global context, but a direct call will execute in whatever context it's in. The `(0, eval)` makes it an indirect call by evaluating an expression that returns the function. This is really timely. I just ran into an issue this weekend where I tried to generalize a function call like this (unaware of the direct vs. indirect semantics), and TypeScript yelled at me about it. Looks like it was trying to evaluate it in the global context, so the error makes sense now.
- wiktor-k 8y agoThis is correct, for details this is specified as point 15.1.2.1 in ES spec: > (...) any invocation of eval that is not a direct call uses the global environment as its variable environment rather than the caller’s variable environment. Source: https://ecma-international.org/ecma-262/5.1/ https://ecma-international.org/ecma-262/5.1/
- chii 8y agoahh, so this only applies to the 'eval' function, and not just any functions it seems.