我一直在学习node.js和模块,并且似乎无法使Underscore库正常工作......似乎我第一次使用Underscore中的函数时,它会覆盖_对象的结果我的函数调用.有谁知道发生了什么?例如,这是来自node.js REPL的会话:
Admin-MacBook-Pro:test admin$ node
> require("./underscore-min")
{ [Function]
_: [Circular],
VERSION: '1.1.4',
forEach: [Function],
each: [Function],
map: [Function],
inject: [Function],
(...more functions...)
templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
template: [Function] }
> _.max([1,2,3])
3
> _.max([4,5,6])
TypeError: Object 3 has no method 'max'
at [object Context]:1:3
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:81:20)
at ReadStream._emitKey (tty_posix.js:307:10)
at ReadStream.onData (tty_posix.js:70:12)
> _
3
Run Code Online (Sandbox Code Playgroud)
当我自己制作Javascript文件并导入它们时,它们似乎正常工作.也许Underscore图书馆有一些特别的东西?
当我注意到这件事时,我正在使用一些代码在Node.js中玩:
> 'hello world'.padEnd(20);
'hello world '
> 'hello world'.padEnd(20, _);
'hello worldhello wor'
Run Code Online (Sandbox Code Playgroud)
下划线符号在这里做什么?
> _
'hello worldhello wor'
Run Code Online (Sandbox Code Playgroud) 我在NodeJS shell中发现了以下行为:
$ node
> function foo () { _ }
undefined
> _
undefined
Run Code Online (Sandbox Code Playgroud)
为什么_定义变量?我期望得到ReferenceError: _ is not defined.
如果我创建一个箭头函数,_它将是函数引用:
$ node
> () => _
[Function]
> _
[Function]
> _.toString()
'() => _'
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
调用后toString()的_变量时,_被转换成字符串:
> _
'() => _'
Run Code Online (Sandbox Code Playgroud)
我尝试使用_ => (),我们有同样的问题:
$ node
> _ => {}
[Function]
> _
[Function]
> _.toString()
'_ => {}'
> _
'_ => {}' …Run Code Online (Sandbox Code Playgroud)