CoffeeScript中的$(document).on和($ document).on之间的区别?

jon*_*ona 4 javascript jquery domdocument coffeescript

我的朋友正在使用($ document).on他的CoffeeScript代码.这与通常的不同$(document).on,如果是这样,以什么方式?

fir*_*oit 5

在CoffeeScript中,使用参数调用函数不需要括号.

例如:

console.log("Hello") // Hello
console.log "Hello"  // Hello
Run Code Online (Sandbox Code Playgroud)

所以,请考虑这些是等价的:

$document = $(document)
$document = $ document
$document = ($ document)
Run Code Online (Sandbox Code Playgroud)

但是,在某些情况下,括号是消除意义歧义所必需的.

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

$(document).on() // on function called on the return of $() function
Run Code Online (Sandbox Code Playgroud)

但这不会按预期工作:

$ document.on() // $() function called with document.on() return!
Run Code Online (Sandbox Code Playgroud)

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

($ document).on() // on function called on the return of $() function
Run Code Online (Sandbox Code Playgroud)

请注意,根据CoffeeScript样式指南,

不建议使用功能分组样式.

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