当我在 node 中输入这个时.js,我得到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).

推荐答案

当使用var时,它在 node 中不起作用,因为testContextlocal of the current module.你应该直接引用它:console.log(testContext);.

当你不输入var时,结果是testContext现在是a global var in the entire Node process.

在Chrome(或任何其他浏览器——嗯,我不确定oldIE…)中,在你的例子中,不管你是否使用vartestContext will go to the global context,也就是window.

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

Node.js相关问答推荐

如何使用多个参数完成

控制台显示一个长对象,我可以';每当我发布更新Mongoose数据库的请求时,我都不知道错误是什么,

当变量在另一个文件中初始化时,在初始化错误之前无法访问变量

React原生Nodejs兼容性问题

为什么 docker 容器内的应用程序无法访问它自己的 API 端点?

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

Mongoose post中间件触发deleteMany

为什么它无法发送发布请求并更改为 chrome 中的获取方法?

我应该如何解决这个 Angular node 包模块依赖冲突?

在系统启动时启动本地 node 服务器

使用 create-expo-app 时如何更改 webpack-config.js 中的哈希函数?

npm chokidar 触发事件两次

获取数组的至少一个元素包含子字符串的文档

突然 React 无法执行create-react-app命令.为什么会发生这种情况,我该如何解决?

Aptana Studio 是否有 NodeJS 插件?

为什么 JavaScript 的 parseInt(0.0000005) 打印5?

如何将`yarn.lock`与`package.json`同步?

如何在 Node.js 中使用 chmod

如何从命令行在 Node.js 上运行 Jasmine 测试

响应分块时获取整个响应正文?