全局变量
window,但 Node 和 Web Worker 没有window。self也指向顶层对象,但是 Node 没有self。global,但其他环境都不支持。同一段代码为了能够在各种环境,都能取到顶层对象,现在一般是使用this变量,但是有局限性。
this会返回顶层对象。但是,Node 模块和 ES6 模块中,this返回的是当前模块。this,如果函数不是作为对象的方法运行,而是单纯作为函数运行,this会指向顶层对象。但是,严格模式下,这时this会返回undefined。new Function(‘return this‘)(),总是会返回全局对象。但是,如果浏览器用了CSP(Content Security Policy,内容安全政策),那么eval、new Function这些方法都可能无法使用。综上所述,很难找到一种方法,可以在所有情况下,都取到顶层对象。下面是两种勉强可以使用的方法。
// 方法一
(typeof window !== ‘undefined‘   ? window   : (typeof process === ‘object‘ &&      typeof require === ‘function‘ &&      typeof global === ‘object‘)     ? global     : this);// 方法二var getGlobal = function () {  if (typeof self !== ‘undefined‘) { return self; }  if (typeof window !== ‘undefined‘) { return window; }  if (typeof global !== ‘undefined‘) { return global; }  throw new Error(‘unable to locate global object‘);};global作为顶层对象。也就是说,在所有环境下,global都是存在的,都可以从它拿到顶层对象。垫片库system.global模拟了这个提案,可以在所有环境拿到global。
// CommonJS 的写法
require(‘system.global/shim‘)();// ES6 模块的写法import shim from ‘system.global/shim‘; shim();global对象都是存在的。// CommonJS 的写法
var global = require(‘system.global‘)();// ES6 模块的写法import getGlobal from ‘system.global‘;const global = getGlobal();global。原文:https://www.cnblogs.com/U5B89/p/9582384.html