将Underscore模块与Node.js一起使用

Geo*_*off 146 module node.js underscore.js

我一直在学习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图书馆有一些特别的东西?

Eri*_*vez 193

截至今天(2012年4月30日),您可以像往常一样在Node.js代码上使用Underscore.以前的注释正确指出REPL接口(Node的命令行模式)使用"_"来保存最后的结果但您可以在代码文件上自由使用它,并且通过执行标准可以正常工作:

var _ = require('underscore');
Run Code Online (Sandbox Code Playgroud)

快乐的编码!

  • 曾经有人告诉我,Globals对所有开发语言都不好.我没有看到在需要它的模块上指定var _ = require('underscore')的问题.http://nodejs.org/api/modules.html#modules_caching (8认同)
  • 请注意,如果您尝试全局化下划线,则不起作用:https://gist.github.com/3220108 (7认同)

Mik*_*ott 169

Node REPL使用下划线变量来保存最后一个操作的结果,因此它与Underscore库使用相同的变量冲突.尝试这样的事情:

Admin-MacBook-Pro:test admin$ node
> _und = 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] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6
Run Code Online (Sandbox Code Playgroud)

  • 感谢你,我一直在用键盘敲打我的头30分钟! (6认同)
  • 这就是SO很棒的原因.这样的好答案可以节省数小时的"头撞".谢谢@Mike (3认同)
  • 谢谢.那很简单. (2认同)

mic*_*rub 28

要么 :

    var _ = require('underscore')._;
Run Code Online (Sandbox Code Playgroud)

  • 首先是"npm install underscore" (21认同)
  • [为什么你不应该'npm install -g`](https://spin.atomicobject.com/2016/02/22/npm-install-dangerous/) (6认同)
  • `npm install -g下划线`,你的意思是:) (3认同)

dki*_*kin 13

该名称_由使用node.jsREPL保留以前的输入.选择其他名称.

  • __双下划线?:) (10认同)
  • 双下划线比_und更好:)我觉得:) (3认同)