4 ms·
I can't for the life of me figure out what the right-hand side of this is doing (from https://github.com/shichuan/javascript-patterns/blob/master/general-patter
by eric_the_read 14y ago
I can't for the life of me figure out what the right-hand side of this is doing (from https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/access-to-global-object.html https://github.com/shichuan/javascript-patterns/blob/master/...):
var global = (function () {
return this || (1, eval)('this');
}());
Why not just use 'this'?
- bulatb 14y agoThe comma operator takes two expressions, evaluates them both, and returns the second. In this case, (1, eval) becomes a reference to the eval function and then gets fed 'this'. Since the call is now indirect, the eval happens in the global scope where 'this' is guaranteed to be the global object. It's kind of crazy. Details here: http://tinyurl.com/3mzf89r http://tinyurl.com/3mzf89r The right side is needed for ES5 strict mode, where `this` does not become the global object in a function that wasn't called with `new`, call(), or apply(). In that case the left side will be something falsy and the right side will take over. Details here: http://tinyurl.com/cwbxvxh http://tinyurl.com/cwbxvxh
- eric_the_read 14y agoThanks! I knew what the comma operator was doing, but had no idea why.
- brodney 14y agoGood discussion here [0]. I didn't know either until reading it. [0] http://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript http://stackoverflow.com/questions/9107240/1-evalthis-vs-eva...
- deleted 14y ago[deleted]