Node.js 变量声明和作用域 [英] Node.js variable declaration and scope

查看:20
本文介绍了Node.js 变量声明和作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 node.js 中输入这个时,我得到 undefined.

var testContext = 15;函数 testFunction() {console.log(this.testContext);}测试函数();=> 未定义

没有 var 关键字,它通过 (=>15).它在 Chrome 控制台中工作(有和没有 var 关键字).

解决方案

使用 var 时在 Node 中不起作用,因为 testContextlocal of当前模块.您应该直接引用它:console.log(testContext);.

当你不输入var时,testContext现在是整个Node进程中的一个全局变量..>

在 Chrome(或任何其他浏览器 - 好吧,我不确定 oldIE ...)中,在您的示例中是否使用 var 并不重要,testContext 将转到全局上下文,即window.

顺便说一句,全局上下文"是JS中函数调用的默认this.

When I type this in node.js, I get undefined.

var testContext = 15;
function testFunction() {
  console.log(this.testContext);
}
testFunction();
=>undefined

Without var keyword, it passes (=>15). It's working in the Chrome console (with and without var keyword).

解决方案

It doesn't work in Node when using var because testContext is a local of the current module. You should reference it directly: console.log(testContext);.

When you don't type var, what happens is that testContext is now a global var in the entire Node process.

In Chrome (or any other browser - well, I'm unsure about oldIE...), it doesn't matter if you use var or not in your example, testContext will go to the global context, which is window.

By the way, the "global context" is the default this of function calls in JS.

这篇关于Node.js 变量声明和作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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