【问题标题】:Difference between $(document).on and ($ document).on in CoffeeScript?CoffeeScript 中 $(document).on 和 ($ document).on 之间的区别?
【发布时间】:2015-01-09 09:59:16
【问题描述】:

我的朋友在他的 CoffeeScript 代码中使用了($ document).on。这与通常的$(document).on 有什么不同吗?如果有,有什么不同?

【问题讨论】:

  • 只是一个带括号的函数调用;换句话说,它相当于 ($(document)).on 的 CoffeeScript
  • @Pointy 所以这一切只是增加了文件的大小?
  • 我不是 CoffeeScript 人,但可能需要使 . 表达式正常工作。换句话说,如果没有额外的()$ document.on 可能会被错误地解释。 (顺便说一句,这将在我不是 CoffeeScript 人的原因列表中:)

标签: javascript jquery coffeescript domdocument


【解决方案1】:

在 CoffeeScript 中,带参数调用函数不需要括号。

例如:

console.log("Hello") // Hello
console.log "Hello"  // Hello

所以,认为这些是等价的:

$document = $(document)
$document = $ document
$document = ($ document)

但是,在某些情况下,括号对于消除歧义是必要的。

例如,您希望在 $() 函数返回时调用 on 函数:

$(document).on() // on function called on the return of $() function

但这不会按预期工作:

$ document.on() // $() function called with document.on() return!

因此,为了强制在 $() 函数的结果上调用 on 函数,我们添加了括号:

($ document).on() // on function called on the return of $() function

请注意,根据CoffeeScript style guide

不推荐使用函数分组样式。

所以建议你的朋友停止使用它:)

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多