【问题标题】:Underscore doesn't work in Coffeescript's console下划线在 Coffeescript 的控制台中不起作用
【发布时间】:2013-12-29 02:54:40
【问题描述】:

我刚刚开始使用 Coffeescript、Coffeescript 控制台和 Underscore。但是,每当我定义一个函数时,Coffeescript 都会确定 _ 表示该函数,并且似乎忘记了 _ = require 'underscore' 的初始分配。

为什么会这样?如何预防?
(我真的希望能够将粘贴代码从我的文件复制到控制台中。)

_ 在 Coffeescript 控制台中有什么特殊含义吗?它的意思是“最后一个结果”还是什么?这可以解释我的问题吗?)

详情:

$ coffee 
coffee> _.contains [1, 2, 3], 3   # no Underscore, initially
TypeError: Cannot call method 'contains' of undefined
    at ...
coffee> 
coffee> _ = require 'underscore'
{ [Function]
  _: [Circular],
  VERSION: '1.3.3',
  forEach: [Function],
  ...

coffee> _.contains [1, 2, 3], 3    # now Underscore works fine
true
coffee> 
------> someFunction = (a, b) ->   # define a function ...
......>   a + b

[Function]
coffee> 
coffee> _.contains [1, 2, 3], 3     # now `_` is not Underscore any more!
TypeError: Object function (a, b) {    # Does `_` mean "last result" or sth?
  return a + b;
} has no method 'contains'
    at evalmachine.<anonymous>:3:7
    at Object.eval (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:142:17)
    at Interface.<anonymous> (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:131:40)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)
    at ReadStream.<anonymous> (readline.js:82:12)
    at ReadStream.emit (events.js:88:20)
    at ReadStream._emitKey (tty.js:327:10)
coffee> 
coffee> _ = require 'underscore'
coffee> _.contains [1, 2, 3], 3    # Now all is fine again, for a short while
true

【问题讨论】:

    标签: coffeescript underscore.js


    【解决方案1】:

    CoffeeScript REPL 的核心是 this JavaScript

    try {
      _ = global._;
      returnValue = CoffeeScript["eval"]("_=(" + code + "\n)", {
        filename: 'repl',
        modulename: 'repl'
      });
      if (returnValue === void 0) {
        global._ = _;
      }
      repl.output.write("" + (inspect(returnValue, false, 2, enableColours)) + "\n");
    } catch (err) {
      error(err);
    }
    

    所以如果最后一个命令返回了一些东西,那么_ 就是那个东西。虽然我找不到任何关于此的文档,但搜索 _ 并不是一项非常有成效的活动。如果您想在 CoffeeScript REPL 中使用 Underscore.js,则必须将其命名为 _ 以外的其他名称。

    感谢Trevor Burnham(谁写了the book,所以我认为我们可以相信他)我们知道CoffeeScript REPL使用_作为匹配node.js REPL行为的最后结果:

    REPL 功能
    [...]
    特殊变量_(下划线)包含最后一个表达式的结果。

    Ruby 的irb 做同样的事情。

    【讨论】:

    • 正确,简短的回答:_ 确实意味着“最后的结果”。这没有很好地记录,但它是为了与node REPL 保持一致。唉,这意味着您必须将 Underscore 映射到其他标识符。
    • 我认为最佳实践是在 CoffeeScript REPL 中使用 __(两个下划线)作为下划线:__ = require 'underscore'
    • 在将现有代码复制/粘贴到 REPL 时,这非常令人沮丧。我发现的最好的事情是设置__ = require "underscore",然后在你想要执行的任何代码之前在REPL中输入__&lt;enter&gt;。 (__&lt;enter&gt; 将返回下划线,因此_ 将指向下划线库以用于下一个运行的命令。)
    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 2018-08-18
    • 1970-01-01
    • 2013-02-04
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多