I start to read JavaScript Patterns, some codes confused me.
var global = (function () {
return this || (1, eval)('this');
}());
Here are my questions:
Q1:
(1, eval) === eval?
Why and how does it work?
Q2: Why not just
var global = (function () {
return this || eval('this');
}());
or
var global = (function () {
return this;
}());
The difference between
(1,eval)and plain oldevalis that the former is a value and the latter is an lvalue. It would be more obvious if it were some other identifier:That is
(1,eval)is an expression that yieldseval(just as say,(true && eval)or(0 ? 0 : eval)would), but it’s not a reference toeval.Why do you care?
Well, the Ecma spec considers a reference to
evalto be a “direct eval call”, but an expression that merely yieldsevalto be an indirect one — and indirect eval calls are guaranteed to execute in global scope.Things I still don’t know:
thisof a function at global scope not yield the global object?Some more information can be gleaned here.
EDIT
Apparently, the answer to my first question is, “almost always”. A direct
evalexecutes from the current scope. Consider the following code:Not surprisingly (heh-heh), this prints out:
EDIT
After more experimentation, I’m going to provisionally say that
thiscannot be set tonullorundefined. It can be set to other falsy values (0, ”, NaN, false), but only very deliberately.I’m going to say your source is suffering from a mild and reversible cranio-rectal inversion and might want to consider spending a week programming in Haskell.