全局对象/作用域和未定义的循环引用

我不确定我是否了解这几个经验的结果:

经验n°1(在新的命令行中):

> _ ReferenceError: _ is not defined at repl:1:2 at REPLServer.self.eval (repl.js:110:21) at Interface.<anonymous> (repl.js:239:12) at Interface.EventEmitter.emit (events.js:95:17) at Interface._onLine (readline.js:202:10) at Interface._line (readline.js:531:8) at Interface._ttyWrite (readline.js:760:14) at ReadStream.onkeypress (readline.js:99:10) at ReadStream.EventEmitter.emit (events.js:98:17) at emitKey (readline.js:1095:12) > global { global: [Circular], ... _: [Circular], } > _ { global: [Circular], ... _: [Circular], } 

体验n°2(在新的命令行中):

 > _ ReferenceError: _ is not defined at repl:1:2 at REPLServer.self.eval (repl.js:110:21) at Interface.<anonymous> (repl.js:239:12) at Interface.EventEmitter.emit (events.js:95:17) at Interface._onLine (readline.js:202:10) at Interface._line (readline.js:531:8) at Interface._ttyWrite (readline.js:760:14) at ReadStream.onkeypress (readline.js:99:10) at ReadStream.EventEmitter.emit (events.js:98:17) at emitKey (readline.js:1095:12) > var http = require('http'); undefined > _ undefined > global._ undefined > global { global: [Circular], ... _: [Circular], } 

经验n°3(在新的命令行):

 > _ ReferenceError: _ is not defined at repl:1:2 at REPLServer.self.eval (repl.js:110:21) at Interface.<anonymous> (repl.js:239:12) at Interface.EventEmitter.emit (events.js:95:17) at Interface._onLine (readline.js:202:10) at Interface._line (readline.js:531:8) at Interface._ttyWrite (readline.js:760:14) at ReadStream.onkeypress (readline.js:99:10) at ReadStream.EventEmitter.emit (events.js:98:17) at emitKey (readline.js:1095:12) > Object.prototype.toString.call(global._) '[object Undefined]' > _ '[object Undefined]' 

所以这就是我直到现在所了解的:

  1. 从经验1号:

    • global对象是在第一个get global触发时build立的。
    • _循环引用也被添加(这似乎是合乎逻辑的)。
  2. 从经验2号:

    • 在访问global对象的属性require()在这种情况下为require() )之后, _被设置。
    • 出于某种原因,它被设置,但是没有被undefined为循环引用。
  3. 从经验3号:

    • 当通过global对象( global._ )中的属性来访问_并将其用作方法或语句的参数时,所述操作的结果将_的值重新分配给该结果。

所以这是我的问题:

  • 为什么不能立即访问循环引用,与像require这样的其他全局属性相比呢?

  • 为什么使用global._重新分配_的方法/语句的结果?

  • 在访问像require这样的其他全局属性之后,为什么_的值被设置为undefined而不是[Circular]

先谢谢你 !

为什么使用global._重新分配_的方法/语句的结果?

_保存上次评估语句的值:

 > 'foo' 'foo' > _ 'foo' > var http = require('http'); undefined > _ undefined 

因此,这不是_的使用,改变_ ,它正在做任何改变_ 。 它最初没有声明,因为没有先前的声明。

在访问像require这样的其他全局属性之后,为什么_的值被设置为undefined而不是[Circular]

你在第一个例子中看到[Circular]的唯一原因是因为_刚刚被设置为global (因为global是最后被评估的语句),所以global._循环地指向global 。 如果您的赋值语句带有require ,那么该行会产生undefined的值,因此这是放在_的值。