14

当我在控制台中运行 node 并键入var _ = require('underscore');时,_最终未定义。如果我将相同的代码放在一个文件中并执行它,则下划线库会按预期包含在内。

$ node
> var _ = require('underscore');
> console.log(_)
undefined // underscore library does not load
> var async = require('async');
undefined
> console.log(async) // async library does
{ noConflict: [Function],
  nextTick: [Function],
  forEach: [Function],
...
>

但是 .js 文件中执行的相同代码node test.js显示两个库都按预期加载。这是怎么回事?

4

1 回答 1

31

Node repl 绑定_到最后评估的输入的值;这会覆盖您_var _ = ...;. 另请参阅repl 上的 node.js 文档

无论替换什么都是如此...,例如:

$ node
> var _ = "any value";
undefined
> _
undefined
于 2012-05-23T01:01:08.940 回答