首页 > 解决方案 > 如何在 TypeScript 中获取全局变量?

问题描述

我的意思是预设的全局变量,例如global在 Node 和window浏览器中。我怎样才能得到它们?

下划线获取全局变量如下:

var root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || this || {};
root._ = _;

标签: typescript

解决方案


 declare var global: any;
 declare var window: any;

 var root: any = null;

 try {
    root = typeof global === 'object' ? global : window;
 } catch(e) {
    // catch is when you are executing in custom V8 where it is
    // configured to throw instead of assuming undefined..
 }

 if (root) {

       // either global or window is present here..
 }

推荐阅读