“root=..”的目的是什么?的代码

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

本文关键字:是什么 代码 root      更新时间:2023-09-26

Async库中有这样一段代码:

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

这些代码有什么原因吗?为什么作者不直接用root = this呢?

第一个条件只在this === window时有效,所以root = windowroot = this应该是等价的。第二种情况也是一样,root = global应该等于root = this

我错过了什么吗?

这不仅是多余的,而且似乎还有bug。

在你的代码片段之前,有这个:

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

目标是将全局对象赋值给root

这样的库应该被编码为在严格模式下工作(不仅在严格模式下,而且至少应该是兼容的)。在严格模式下,IIFE执行的上下文是undefined。这段代码总是无法在严格模式下找到根对象,无论是在节点上还是在浏览器中。

注意,有一些可靠的方法可以找到根对象。标准的方法是间接调用:

var root = (1,eval)('this');