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;
?
It’s getting a reference to the global object, in order to assign
doTto 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 alwayswindow, for example, in a non-browser environment. It’s also possible to havewindowassigned to somewhere else at the point this code is executed.How it works
If
thisis already truthy, for example, an object such aswindow, it will return that. It’s likely it will bewindow(at least in the browser), as a plain function call should have itsThisBindingset to the global object. Otherwise, it will executeeval()in the global scope because an indirect call toeval()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 witheval(). You can use(0, eval)to invoke it. This relies on the comma operator returning the last evaluated expression, in this caseeval. 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 toeval(), that is the code to be executed as a string. It will return thethisin 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.