9

There's this snippet of code in the Async library:

if (typeof window == 'object' && this === window) {
    root = window;
}
else if (typeof global == 'object' && this === global) {
    root = global;
}
else {
    root = this;
}

Is there any reason for all this code? Why didn't author just use root = this?

The first condition is only valid when this === window, so root = window and root = this should be equivalent. Same thing in the second condition, where root = global should be equivalent to root = this.

Am I missing something here?

Fczbkk
  • 1,477
  • 1
  • 11
  • 23
  • 1
    [I asked the author](https://twitter.com/DenysSeguret/status/606427206806568960). He'll probably give a better answer than mine ;) – Denys Séguret Jun 04 '15 at 11:48

1 Answers1

7

Not only it is redundant, it also seems to be buggy.

Just before your snippet, there's this :

// global on the server, window in the browser
var root, previous_async;

So the goal is to assign to root the global object.

Such a library should be coded to work in strict mode (not only in strict mode but it should at least be compliant). And in strict mode, the context of an IIFE execution is undefined. This code would always fail to find the root object in strict mode, both on node and in the browser.

Note that there are reliable ways to find the root object. The standard one is to do an indirect call:

var root = (1,eval)('this');
Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • *not like redundant code*. Can you explain why not? Assuming that strict mode is not supported by the library, this doesn't answer the original question. – CodingIntrigue Jun 04 '15 at 11:19
  • @RGraham "Assuming that strict mode is not supported", this is obviously a redundant code. But assuming this is like assuming this library is obsolete since a very long time. There was an intention justifying so much code and I think I explained it what it was, it's just buggy because it uses `&&` instead of `||`. – Denys Séguret Jun 04 '15 at 11:22
  • But the `use strict` would have to be defined globally for your use case to have been hit, right? Which isn't standard practice I wouldn't have thought. In any case, I don't really have a problem with your answer but I was interested in why exactly the code *is redundant* other than simply "it is". – CodingIntrigue Jun 04 '15 at 11:27
  • @DenysSéguret BTW your code will always fail in Node with `ReferenceError`. Most likely it should not contain `||` at all, `typeof` checks would be enough – Eugene Jun 04 '15 at 11:28
  • in Node `window` is not defined, so `this === window` comparison will throw – Eugene Jun 04 '15 at 11:31
  • @Zhegan Yes, you're right (I removed my previous comment). I fail to see how the existing code looked like a good idea. – Denys Séguret Jun 04 '15 at 11:32