CoffeeScript默认参数

时间:2014-05-20 15:17:39

标签: coffeescript

我正在查看CoffeeScript: Accelerated Development

中的以下示例
x = true
showAnswer = (x = x) ->
  console.log if x then 'It works!' else 'Nope.'

console.log "showAnswer()", showAnswer()
console.log "showAnswer(true)", showAnswer(true)
console.log "showAnswer(false)", showAnswer(false)

我不明白为什么showAnswer(...) undefined出现在每个测试中。

Nope.
showAnswer() undefined
It works!
showAnswer(true) undefined
Nope.
showAnswer(false) undefined

请解释每个案例的输出。

1 个答案:

答案 0 :(得分:3)

不要忘记CoffeeScript默认返回函数中的最后一个语句。那么你的showAnswer函数实际上是说:

showAnswer = (x = x) ->
    return console.log if x then 'It works!' else 'Nope.'

或编译为JavaScript:

showAnswer = function(x) {
  if (x == null) {
    x = x;
  }
  return console.log(x ? 'It works!' : 'Nope.');
};

要实现的另一件事是console.log方法返回undefined。因此,当您记录showAnswer方法的结果时,它会打印undefined

如果我理解你的意图,我会修改你原来的功能来做到这一点:

showAnswer = (x = x) ->
  if x then 'It works!' else 'Nope.'

或者,修改您的console.log语句:

console.log "showAnswer()"
showAnswer()

console.log "showAnswer(true)"
showAnswer(true)

console.log "showAnswer(false)"
showAnswer(false)