Hacker News new | past | comments | ask | show | jobs | submit login

I can not visualize what you mean. What does it mean to be run as the eval function itself?



It's the dorkiest thing you can imagine, literally a string comparison against "eval".

In JS functions are first class, so one might attempt:

    function wut() {
      var x = 1;
      var obj = {sneaky: eval};
      obj.sneaky("x++");
      console.log(x);
    }

Here we are calling `obj.sneaky()` with some JS code. The sneaky property is the eval function: won't it run the code and thereby increment x?

The answer is no: because the caller's name 'obj.sneaky' does not literally compare equal to "eval", the eval function is run with global scope instead of local scope. Therefore the 'x' inside the eval'd string is a global property, not the local variable.

So with this analysis we can (statically) apply constant propagation and replace x with 1.

Now if we replace obj.sneaky with eval, the string comparison succeeds, it becomes "direct eval", and the constant propagation is invalid.


Since this seems such a roundabout way of calling eval, does anyone actually use this?


Well usually we want to run code at global scope, and direct eval is an obstacle.

There's workarounds like "(1, eval)", but the most idiomatic way is the Function constructor, which always runs code at global scope. That leads to this pattern:

    var global = (new Function("return this")())
which really is the safest way to get the global object. I know right.


TIL. I love this.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: