YuzuJS/setImmediate

Why not just use "this"

luckydrq opened this issue · 3 comments

  (function() {
     ...
  })(new Function("return this")())

What's the difference between simply using this and new Function("return this")()?

new Function("return this")() is a form of indirect eval, which prevents access to the local scope. It is just a way to make sure you're accessing the global namespace (as is hinted at by the parameter name global on line 1 of setImmediate.js ). As far as I know, it is basically the same as writing:

(function() {
  return (0, eval)("this");
})()

as opposed to direct eval, which allows access to the current local scope:

(function() {
  return eval("this");
})()

or just using whatever this you happen to be handed via call, apply, or bind.

For example,

var newFunctionStyle = function() {
  return new Function("return this;")();
}

var indirectEvalStyle = function() {
  return (0, eval)("this");
}

var directEval = function() {
  return eval("this");
}

var justThis = function() {
  return this;
}

var a = { ham: "sandwich" };

newFunctionStyle.call(a); // Window in browser or global in node
indirectEvalStyle.call(a); // Window in browser or global in node
directEval.call(a); // {ham: "sandwich"}
justThis.call(a); // {ham: "sandwich"}

The important part is that the function setImmediate should be globally available after the code in setImmediate.js is run, even if it is executed in an arbitrary scope, possibly in a mass of other scripts all concatenated together.

@aaylward Thank you for your explanation! I also found this article for futher study. In this post, it explains how function created via Function behaves:

The code executed from within function created by Function constructor doesn’t really execute in global scope. However, it doesn’t execute in local scope either, which is what probably leads to confusion. Function constructor creates a function whose scope chain consists of nothing but a global scope (preceded with function’s own Activation Object, of course). Any code contained in a function created via Function constructor evaluates in a scope of that function, not in a global scope. However, it’s almost as if code executes globally, since global object is the very next object in the scope chain.

That's an awesome article! Thanks for following up!