为什么coffeescript会覆盖我的下划线?

lim*_*imp 1 javascript coffeescript

我编写了以下代码,旨在将字符串连接到一个URL.

_ = require 'underscore'

exports.joinUrl = (start, rest...) ->
  for item in rest
    if _.last start is '/'
      if _.first item is '/'
        start += item[1..]
      else
        start += item
    else
      if _.first item is '/'
        start += item
      else
        start += '/' + item
  start
Run Code Online (Sandbox Code Playgroud)

当我启动coffeescript repl时,会发生一件非常奇怪的事情:

> _ = require 'underscore'
[snipped]
> {joinUrl} = require './joinurl'
{ joinUrl: [Function] }
> _
{ joinUrl: [Function] }
Run Code Online (Sandbox Code Playgroud)

咦?不知何故导入joinUrl是覆盖变量的定义_.即使(a)coffeescript将上面粘贴的模块包装到一个函数中,因此变量的任何使用_都不应该影响外部范围,并且(b)在该代码中的任何一点我都不做任何赋值_,除了require 'underscore',这应该是完全相同的东西!

知道这里发生了什么吗?

Ber*_*rgi 5

就像在Python中一样,REPL使每个表达式结果都可用_,就像在

> 5
5
> _ + 3
8
Run Code Online (Sandbox Code Playgroud)

你的代码被翻译成类似的东西

> _ = (_ = require 'underscore')
[snipped]
> _ = ({joinUrl} = require './joinurl')
{ joinUrl: [Function] }
> _ = (_)
{ joinUrl: [Function] }
Run Code Online (Sandbox Code Playgroud)

  • @limp_chimp:为了清楚起见,这是REPL的一个功能,而不是CoffeeScript本身.它只是意味着在REPL中,你需要为Underscore使用不同的名称.您仍然可以在所有代码中使用_. (4认同)