Hacker News new | past | comments | ask | show | jobs | submit login

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/...):

  var global = (function () {
    return this || (1, eval)('this');
  }());
Why not just use 'this'?



The 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

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


Thanks! I knew what the comma operator was doing, but had no idea why.


Good discussion here [0]. I didn't know either until reading it.

[0] http://stackoverflow.com/questions/9107240/1-evalthis-vs-eva...




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: