node.js - 关于node下全局变量的问题
迷茫
迷茫 2017-04-17 13:00:44
[Node.js讨论组]

如下代码,按照常理,全局作用域下申明的变量会自动成为全局对象下的一个属性

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

但是这个代码在不同的执行方法下好像出现了不同的预期,入下图,直接node + file文件名执行发现找不到this.a
如右边的一步步走的话发现是能找到this.a的,这其中是否有什么不同?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
天蓬老师

对于代码写在文件中的情况,其实一个文件就是一个 CommonJS 模块,node 会对该模块加一层包裹,因此,你上面的代码最终是变成下面这样进行运行的:

(function (exports, require, module, __filename, __dirname) {
    var a = 2;
    function foo(){
        console.log(this.a);
    }
    foo();
})

所以,很明显了, var a = 2 并不是全局变量,如果用想访问全局变量的话最好是用 global

但是直接在控制台中运行的代码是不会进行模块包装的。

ringa_lee

有意思的问题,查了一下资料:
http://stackoverflow.com/questions/19850234/node-js-variable-declaration-and-scope

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 REPL中,为什么又和浏览器的行为类似了,这个我不太清楚,同求该答案。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号