[英]NodeJS global variable not reassignable
I am trying to unit test code that uses JavaScript library that is set a global variable if it does not exist.我正在尝试对使用 JavaScript 库的代码进行单元测试,如果它不存在则设置为全局变量。 The pattern the library is using is:
图书馆使用的模式是:
var GLOBAL_VAR = GLOBAL_VAR || {}
This works in browser world, but when I execute the code in NodeJS, it does not work.这适用于浏览器世界,但是当我在 NodeJS 中执行代码时,它不起作用。 The problem comes down to this:
问题归结为:
var myGlobal = 'CORRECT';
console.log('Prints CORRECT', myGlobal || 'WRONG');
(function () {
// Why does this print WRONG?
var myGlobal = myGlobal || 'WRONG';
console.log('Prints WRONG', myGlobal);
}).call(this);
(function () {
console.log('Prints CORRECT', myGlobal || 'WRONG');
}).call(this);
Why is the first function printing WRONG while the second function prints CORRECT?为什么第一个 function 打印错误,而第二个 function 打印正确?
You are declaring a local variable myGlobal
inside the first anonymous function.您在第一个匿名 function 中声明了一个局部变量
myGlobal
。 This shadows the global variable.这会影响全局变量。
Then, in the anonymous function, you declare:然后,在匿名 function 中,您声明:
var myGlobal = myGlobal || 'WRONG';
// ^
// | this local variable is undefined here, as
// the global is not accessible with this name
That is why myGlobal
(the local variable) gets the value 'WRONG'
.这就是
myGlobal
(局部变量)获得值'WRONG'
原因。
The solution is to rename the confusingly named local variable myGlobal
in the anonymous function to something that does not shadow the global variable.解决方案是将匿名 function 中命名混乱的局部变量
myGlobal
重命名为不影响全局变量的名称。
Note that you would not have this problem if you used let
as let
does not allow you to use the variable as a value in it's own declaration:请注意,如果您使用
let
as let
不允许您将变量用作它自己的声明中的值,则不会出现此问题:
let x = x || 'WRONG'; // should produce an error and leave x undefined.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.