不使用DOM访问全局JS上下文的属性

Access properties of the global JS context without DOM

本文关键字:JS 上下文 属性 全局 访问 DOM      更新时间:2023-09-26

我想在我的应用程序中访问全局JS作用域的所有属性。

没有DOM,所以我不能使用以下代码:

for (var attr in window) {
  // attr is in the global scope
}

是否有一种方法可以获得对全局JS范围的引用?

在非严格模式下,您可以使用this:

获取对全局对象的引用。
var globalObj = (function(){return this}());
如果你没有在调用中设置this,它默认为全局对象。这将在任何执行上下文中工作(但不是在严格模式下)。创建一个引用全局对象的全局变量更简单:
var global = this;

或传递给IIFE:

(function (global) {
  // In here, global === global object
  ...
}(this))

无论西装。