【问题标题】:Which object does var belong to in NodeJs module?var 在 NodeJs 模块中属于哪个对象?
【发布时间】:2019-09-11 06:56:33
【问题描述】:

这是我的代码

var a=1;
console.log(global.a);
console.log(this.a);

两者都打印undefined。它表明a 不属于global 或this(当前模块)。

我想知道a var 属于哪个对象。

【问题讨论】:

  • 查看repl.it/@MaheerAli/Test 两次都显示日志记录1。你能编辑它以显示问题吗?
  • @MaheerAli 这清楚地提到了 Node.js,它与问题描述的完全一样:Try it online!
  • Tony, a 属于顶级模块作用域,不是语言可访问的对象。
  • @AlexanderNied REPL 与在模块中运行的代码不同。 REPL 在全局范围内评估,模块代码在与模块隔离的函数范围内评估。根据给出的行为描述,上面的代码运行在一个由 Node.js 作为模块评估的文件中。
  • @AlexanderNied 如果您想重现 repl.it 中的行为,该行为似乎直接在 Node.js REPL 中而不是作为模块运行 index.js,请使用 this example。

标签: javascript node.js scope


【解决方案1】:

要理解这一点,您需要了解 Node.js 中的 Module Wrapper。

Node.js 运行的所有 JavaScript 代码都不是直接运行的,而是由 Node 内部调用的函数调用包装的。

模块包装器:

(function (exports, require, module, __filename, __dirname) {  
    // You code goes here  
});

实际运行的代码是:

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

所以var a 在匿名函数的范围内,不是global 对象的一部分,也不是this 的一部分(因为这个函数没有被任何对象调用,即函数​.prototype​.call(空))

参考The module wrapper

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多