Kaj*_*nus 11 coffeescript underscore.js
我刚刚开始使用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
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 20
CoffeeScript REPL的核心是这个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);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果最后一个命令返回了什么,那么_就是那个东西.我找不到任何关于此的文档,但搜索_并不是一项非常有成效的活动.如果你想在CoffeeScript REPL中使用Underscore.js,你必须把它称为其他东西_.
感谢Trevor Burnham(我写这本书所以我认为我们可以相信他)我们知道CoffeeScript REPL使用_最后的结果来匹配node.js REPL的行为:
REPL Features
[...]
特殊变量_(下划线)包含最后一个表达式的结果.
Ruby irb也做同样的事情.
| 归档时间: |
|
| 查看次数: |
1661 次 |
| 最近记录: |