简体   繁体   English

全局变量作用域在Node.js控制台中无法识别

[英]Global Variable Scope Not recognized in Node.js console

So in a browser (chrome), if I run this code in the js console, the function call foo(); 因此,在浏览器(chrome)中,如果我在js控制台中运行此代码,则该函数将调用foo(); prints to the console the number 2. But if I run it in node.js, the function call foo() prints undefined . 将数字2打印到控制台。但是,如果我在node.js中运行它,则函数foo()会打印undefined Why is this the case? 为什么会这样呢? Does node automatically run code in 'strict mode'? 节点是否以“严格模式”自动运行代码?

function foo() {     
   console.log(this.a); 
} 

var a = 2; 

foo();

As mentioned in the document 文件中所述

var something inside an Node.js module will be local to that module. var Node.js模块内部的某些内容对于该模块而言是本地的。

So, it is going to be different. 因此,情况将有所不同。

You can alternatively, try: 您也可以尝试:

function foo() {     
   console.log(this.a); 
} 
global.a = 2; 

foo();

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

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