【问题标题】:global variable assignment in node from script vs command line从脚本与命令行在节点中分配全局变量
【发布时间】:2014-08-16 03:49:06
【问题描述】:

我有以下脚本:

/* script.js */
var bar = "bar1";

function foo() {
    console.log('this.bar: ' + this.bar);
    console.log('global.bar: ' + global.bar);
}
foo();

运行node script.js 返回:

this.bar: undefined
global.bar: undefined

但是,从节点命令行环境内部,复制相同的脚本会返回:

this.bar: bar1
global.bar: bar1

此外,如果我将变量声明从var bar = "bar1"; 更改为global.bar = "bar1";,运行上述代码的两种方法都会返回:

this.bar: bar1
global.bar: bar1

有什么区别?在同一环境中运行脚本与复制脚本时,全局变量分配是否有所不同?

【问题讨论】:

  • 以这种方式运行脚本基本上是在运行一个模块,而一个模块基本上只是你的代码在被eval'd 和调用之前拼接到一个函数中,所以var 是一个局部变量在那个函数中。 REPL 在全局执行上下文中运行。

标签: javascript node.js


【解决方案1】:

只是因为每个节点模块都包装在某种 IIFE 中,所以默认情况下您不在全局范围内。

我们可以看到它发生在 src/node.jsNativeModule 函数中。

NativeModule.require = function(id) {
    // ...
    var nativeModule = new NativeModule(id);

    nativeModule.cache();
    nativeModule.compile();

    return nativeModule.exports;
};

我们追踪compile

NativeModule.prototype.compile = function() {
    var source = NativeModule.getSource(this.id);
    source = NativeModule.wrap(source);

    var fn = runInThisContext(source, { filename: this.filename });
    fn(this.exports, NativeModule.require, this, this.filename);

    this.loaded = true;
};

wrap 看起来很相关,让我们看看它的作用:

NativeModule.wrap = function(script) {
    return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
};

NativeModule.wrapper = [
    '(function (exports, require, module, __filename, __dirname) { ',
    '\n});'
];

正如怀疑的那样,它将你的模块代码包装在一个 IIFE 中,这意味着你不在全局范围内运行。

另一方面,REPL by default 在全局范围内运行。 REPL 代码后面是 meh,但它基本上归结为 this line

if (self.useGlobal) {
    result = script.runInThisContext({ displayErrors: false });
} else {
    result = script.runInContext(context, { displayErrors: false });
}

这看起来与我很相关。

【讨论】:

    【解决方案2】:

    http://nodejs.org/api/globals.html

    Node 模块中的某些内容将是该模块的本地内容。

    我认为当您从文件运行某些内容时,它会被解释为节点的模块。如果您在命令 shell 中执行,范围顶部的变量将变为全局变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      相关资源
      最近更新 更多