如何在使用strict mode pragma时声明全局变量 [英] How to declare global variables when using the strict mode pragma

查看:79
本文介绍了如何在使用strict mode pragma时声明全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用自调用函数来包装严格模式兼容代码被认为是一种好习惯,通常称为严格模式编译指示:

It's considered good practice to use a self-invoking function to wrap strict mode compliant code, often called the strict mode pragma:

(function(){
  "use strict";
  // Strict code here
}());

我的问题是如何在这种情况下声明全局变量?我今天知道的三种选择:

My question is how to declare global variables in this case? Three alternatives that I know of today:

备选1:

var GLOB = {};

(function(){
  "use strict";
}());

备选2:

(function(){
  "use strict";
  window.GLOB = {};
}());

备选3:

(function(win){
  "use strict";
  win.GLOB = {};
}(window));

任何偏好和动机?其他选择?

Any preferences and motivations? Other options?

推荐答案

IMO替代3是最好的。但它假设窗口表示全局范围 - 对于浏览器而言是这样,但对于其他JS环境(命令行,Node.js等)则不然。

IMO alternative 3 is best. But it assumes that window represents the global scope - which is true for the browser but not for other JS environments (command line, Node.js, etc.).

以下内容将全面运作:

(function(globals){
  "use strict";
  globals.GLOB = {};
}(this));

这篇关于如何在使用strict mode pragma时声明全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆