Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of `root=...` code in Async library?

Tags:

javascript

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?

like image 839
Fczbkk Avatar asked Jun 04 '15 11:06

Fczbkk


1 Answers

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');
like image 188
Denys Séguret Avatar answered Oct 31 '22 01:10

Denys Séguret