简体   繁体   English

匿名自执行js函数内部的全局变量在外部仍然可用?

[英]Global variable inside anonymous self-executing js function still available outside?

I have these two javascript files: 我有以下两个JavaScript文件:

test1.js:
(function() {
  console.log(global_var_test2);
})();

test2.js:
(function() {
  global_var_test2 = "test";
})();

Obviously if i use the var keyword in test2.js the global_var_test2 variable will not be available in test1.js..but i thought that when you were wrapping all your code in a file inside a self-executing anonymous functions that you created a separate scope so that variables that were created without the var keyword would still not be visible outside ? 显然,如果我在test2.js中使用var关键字,那么global_var_test2变量将在test1.js中不可用。.但是我认为当您将所有代码包装在文件中时,会创建一个独立的匿名函数作用域,以便在没有var关键字的情况下创建的变量在外部仍然不可见? When running the code above im able to access global_var_test2 inside of test1.js. 当运行上面的代码时,im可以访问test1.js内部的global_var_test2。

If im remembering correct the use of a self-executing anonymous function is almost always used when writing javascript modules to isolate it from the other possibly installed modules you have..but that doesnt seem to work with the code above.. could someone explain why not ? 如果我没记错的话,在编写javascript模块以将其与您可能拥有的其他可能安装的模块隔离时,几乎总是使用自动执行的匿名函数。但这似乎与上面的代码不兼容。不是吗

Your understanding is incorrect. 您的理解不正确。 If you assign to a variable without declaring it with var , you're creating a global variable, wrapper or no wrapper. 如果在不使用var声明变量的情况下分配变量,则将创建全局变量,包装器或无包装器。

In "strict" mode, that would be an error. 在“严格”模式下,这将是一个错误。 Therefore, if you really want to make sure you're not polluting the global environment — which is smart — you put your code in "strict" mode: 因此,如果您确实要确保不污染全局环境(这很聪明),则可以将代码置于“严格”模式:

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

If you accidentally forget var , you get an error. 如果您不小心忘记了var ,则会出现错误。 If you want a global variable, you can check for it: 如果需要全局变量,可以检查一下:

  if ("myGlobalSymbol" in window)
    throw new Error("Something stole myGlobalSymbol from me!");

or whatever. 管他呢。

Variables created with var outside of a function are global - the same as if you had not used var . 使用var在函数外部创建的变量是全局变量-与未使用var
Since you should be defining all of your variables via either var myvar or window.myvar = stuff , immediately invoked functions are used to prevent your var statements from polluting the global environment and potentially causing clashes. 由于您应该通过var myvarwindow.myvar = stuff定义所有变量,因此,立即调用的函数用于防止var语句污染全局环境并可能导致冲突。

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

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