【问题标题】:Node.js variable declaration and scopeNode.js 变量声明和范围
【发布时间】:2013-11-19 22:36:41
【问题描述】:

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

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

没有 var 关键字,它通过 (=>15)。它在 Chrome 控制台中运行(带有和不带有 var 关键字)。

【问题讨论】:

  • 您是否尝试在对console.log() 的调用中删除this.
  • this keyword 在那里做什么?
  • @JustinNiessner 删除 this. 有效。为什么?如果在另一个 node.js 文件中调用了testFunction();,它还可以工作吗? (测试是,但为什么呢?)
  • 发现是javascript的lexical scope

标签: javascript node.js scope


【解决方案1】:

document中所述

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

所以,它会有所不同,因为 var testContext 在模块上下文中,而 this 的上下文是 global

您也可以使用:

global.testContext = 15;
function testFunction() {
  console.log(this.testContext);
}
testFunction();

【讨论】:

    【解决方案2】:

    主要区别在于 Node.js 中的所有模块(脚本文件)都在它们自己的closure 中执行,而 Chrome 和其他浏览器则直接在全局范围内执行所有脚本文件。

    Globals documentation中提到了这个:

    其中一些对象实际上不在全局范围内,而是在模块范围内 - 这将被注明。

    您在 Node 模块中声明的 vars 将被隔离到这些闭包之一,这就是为什么您必须 export members 才能让其他模块访问它们。

    不过,在没有特定上下文的情况下调用function 时,它通常会默认为全局对象——在Node 中方便地称为global

    function testFunction() {
        return this;
    }
    
    console.log(testFunction() === global); // true
    

    而且,如果没有 var 声明它,testContext 将默认为 defined as a global

    testContext = 15;
    console.log(global.testContext); // 15
    

    【讨论】:

    • “关闭”和“范围”我认为您的意思是“执行上下文”。
    • @RobG 它们仍然是有效且常用的术语。但是,是的,ECMA 将它们定义为 Execution Contexts
    • 它们通常使用不正确,其他一些参考:closurescopeexecution context
    • @RobG 我知道每个是什么。但是,区别是迂腐的。这很好,我同意你的看法。但是,“范围”仍然是描述一般概念的有效术语,而[[Scope]]、范围链和执行上下文是更具体的实现细节。
    【解决方案3】:

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

    当您不输入var 时,会发生testContext 现在整个Node 进程中的全局变量

    在 Chrome(或任何其他浏览器 - 好吧,我不确定 oldIE...)中,无论您是否在示例中使用 vartestContext 都会转到全局上下文,即window

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

    【讨论】:

      【解决方案4】:

      我认为问题与this 关键字有关。如果您执行console.log(this),您将看到未定义 testContext。你可以试试:

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

      【讨论】:

        猜你喜欢
        • 2012-06-11
        • 2020-03-18
        • 2014-09-20
        • 1970-01-01
        • 2010-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多