📅  最后修改于: 2023-12-03 15:27:50.160000             🧑  作者: Mango
有时候在开发 JavaScript 代码时,需要了解当前页面或脚本运行时的所有全局变量。这些变量可能是由浏览器和第三方库定义的,它们可以影响应用程序的行为。
在 JavaScript 中,全局变量都可以通过 window 对象来访问。因此,我们可以使用 for...in 循环迭代 window 对象的属性,以获取所有全局变量。代码如下:
let globalVars = [];
for (let prop in window) {
if (window.hasOwnProperty(prop)) {
globalVars.push(prop);
}
}
console.log(globalVars);
注意:我们需要使用 hasOwnProperty 方法过滤掉 window 对象自身的属性,这些属性包括 frame, length, location 等。
输出结果如下:
[
"BigInt",
"Infinity",
"NaN",
"undefined",
"window",
"self",
"document",
"name",
"location",
"history",
"customElements",
"locationbar",
"menubar",
"personalbar",
"scrollbars",
"statusbar",
"toolbar",
"status",
"frames",
"frameElement",
"navigator",
"origin",
"external",
"screen",
"innerWidth",
"innerHeight",
"scrollX",
"pageXOffset",
"scrollY",
"pageYOffset",
"visualViewport",
"screenX",
"screenY",
"outerWidth",
"outerHeight",
"devicePixelRatio",
"clientInformation",
"event",
"performance",
"stop",
"open",
"alert",
"confirm",
"prompt",
"print",
"queueMicrotask",
"requestAnimationFrame",
"cancelAnimationFrame",
"captureEvents",
"releaseEvents",
"requestIdleCallback",
"cancelIdleCallback",
"getComputedStyle",
"matchMedia",
"moveTo",
"moveBy",
"resizeTo",
"resizeBy",
"scroll",
"scrollTo",
"scrollBy",
"getSelection",
"find",
"webkitRequestAnimationFrame",
"webkitCancelAnimationFrame",
"btoa",
"atob",
"setTimeout",
"clearTimeout",
"setInterval",
"clearInterval",
"createImageBitmap",
"fetch",
"Headers",
"Request",
"Response",
"WebSocket",
"AbortController",
"AbortSignal",
"queueMicrotask",
"atob",
"btoa",
"performance",
"po",
"Proxy",
"Promise",
"queueMicrotask",
"requestAnimationFram",
"Reflect",
"RegExp",
"removeEventListener",
"queueMicrotask",
"scroll",
"scrollTo",
"scrollBy",
"queueMicrotask",
"sessionStorage",
"setInterval",
"setTimeout",
"SharedArrayBuffer",
"String",
"Symbol",
"queueMicrotask",
"TextDecoder",
"TextEncoder",
"queueMicrotask",
"URL",
"URLSearchParams",
"queueMicrotask",
"WeakMap",
"WeakSet",
"Array",
"console",
"Error",
// 省略部分结果
]
但是这种方法可能会返回一些不是全局变量的属性,比如 window/document 的方法,因此需要对结果进行筛选处理。
Object.getOwnPropertyNames 方法可以获取对象的所有属性名,包括不可枚举的属性。我们可以使用这个方法获取 window 对象的所有属性,然后排除一些特定的属性(如 proto, constructor),这样就可以得到所有全局变量。代码如下:
let globalVars = Object.getOwnPropertyNames(window)
.filter((prop) => {
return (
typeof window[prop] !== "function" &&
prop !== "__proto__" &&
prop !== "constructor"
);
});
console.log(globalVars);
输出结果与方法一相同。
还可以在代码中插入 debugger 语句,然后在浏览器的开发者工具中打开控制台,查看所有全局变量。
插入 debugger 语句后,代码会停在该位置等待调试器执行指令。此时打开浏览器控制台,可以看到全局变量列表。
debugger;
这种方法不适用于生产环境,只适合于开发调试。
以上是获取 JavaScript 中所有全局变量的方法,可以根据自己的需求选择适合自己的方法。在使用方法一和方法二时,需要排除掉一些不是全局变量的属性,以确保返回的全局变量列表准确。在使用方法三时,需要注意只在开发环境下使用。