简体   繁体   English

带有全局变量的Javascript中有趣的范围问题

[英]Funny scope issue in Javascript with global variables

I have a big JS app with many modules, which will ultimately be bundled with browersify. 我有一个包含许多模块的大型JS应用程序,最终将与browersify.捆绑在一起browersify. But since I don't want to make my whole team install Node.js and rebuild every time they change a character, I want the modules to register globally just while developing. 但是因为我不想让我的整个团队安装Node.js并在每次更改角色时重建,我希望模块在开发时全局注册。 I've been using the standard registration for modules like so: 我一直在使用标准注册模块,如下所示:

// if browserify
if (typeof module === "object" && module.exports) {
    module.exports = myModule;
} else { window.myModule = myModule; }

Here's where it gets funky: When requiring dependencies in the main app.js file, I do this: 这是它变得时髦的地方:当在主app.js文件中需要依赖项时,我这样做:

if (typeof module === "object" && module.exports) {
    var myModule = require("./js/myModule");
} // otherwise it's assumed to be globe, which console.log(window) confirms
console.log(myModule);

This console log comes back as undefined, so I need an else line that says: } else { myModule = window.myModule; 这个控制台日志以未定义的形式返回,所以我需要一个else行:} else {myModule = window.myModule; } }

Here's a simpler jsFiddle as a proof of concept: 这里有一个简单的jsFiddle作为概念证明:

if (false) {
    var test = "Hello World";
} else {
  window.test = "Hello Globe";
}

document.getElementById("console").innerHTML = test;

test is undefined in this scenario. 在这种情况下, test未定义。

What puzzles me is that the contents of the if statement that never runs seems to still register test as a local variable. 让我感到困惑的是,从不运行的if语句的内容似乎仍然将test作为局部变量注册。 Is that what's happening? 那是怎么回事? Or do I just not understand how global variables work? 或者我只是不明白全局变量是如何工作的? I thought anything registered to window could be called by it's own name, just as we don't have to write window.jQuery every time. 我认为注册到window任何内容都可以通过它自己的名称来调用,就像我们不必每次都编写window.jQuery一样。

Javascript hoists var declarations and since you are declaring inside the if statement that's not a new scope, basically having this: Javascript提升var声明,因为你在if语句中声明不是新范围,基本上有这样的:

if (false) {
    var test = "Hello World";
} else {
  window.test = "Hello Globe";
}

It's the same of having this: 有这样的:

var test;
if (false) {
  test = "Hello World";
} else {
  window.test = "Hello Globe";
}

That's why it's a good practice to declare your variables on the beginning of the scope, check this example: 这就是为什么在范围的开头声明变量是一个好习惯,请检查以下示例:

var test = "Hello World From outside";
function(){
  console.log(test);
  if (false) {
    var test = "Hello World From inside"
  }
}

This example will output: "undefined" the var test is hoisted to the top of the scope, in this case the top of the function overwriting the outer variable declaration although we will never enter into that if 这个例子将输出:“不确定”的变种测试提升到范围的顶端,在这种情况下,函数的覆盖外变量声明虽然我们永远不会进入到了顶部if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM