问题
Looking at the doT.js source:
https://raw.github.com/olado/doT/master/doT.js
What does this do?
(function(){ return this || (0,eval)('this'); }()).doT = doT;
To me it looks like it's creating a global var, window.doT
. If that's all it's doing, then why not:
window.doT = doT;
?
回答1:
It's getting a reference to the global object, in order to assign doT
to it. This is generally done because with a JavaScript library/framework/etc, its one global identifier needs to be exposed to the outside world.
As for why it's not simply window.doT = doT;
, it's because the global object isn't always window
, for example, in a non-browser environment. It's also possible to have window
assigned to somewhere else at the point this code is executed.
How it works
If this
is already truthy, for example, an object such as window
, it will return that. It's likely it will be window
(at least in the browser), as a plain function call should have its ThisBinding
set to the global object. Otherwise, it will execute eval()
in the global scope because an indirect call to eval()
will set its scope to global, as opposed to the calling environment's scope.
To achieve an indirect call, you have to invoke eval()
indirectly, i.e. you can't just call it with eval()
. You can use (0, eval)
to invoke it. This relies on the comma operator returning the last evaluated expression, in this case eval
. It doesn't matter what the preceding operands are. Similarly, (0||eval)()
would work.
As for why the body is this
, that is the argument to eval()
, that is the code to be executed as a string. It will return the this
in the global scope, which is always the global object.
It's not really relevant nowadays, but in older IEs, you'd need to use execScript()
to execute code in the global scope. I can't remember exactly what versions of IE this was necessary for.
来源:https://stackoverflow.com/questions/14119988/return-this-0-evalthis