如何在浏览器中使用 CoffeeScript 正确确定函数范围?
(->
jQuery ->
globalThis = @
$('#emailTypes').change ->
globalThis.toggleEmailOptions()
toggleEmailOptions = ->
$('.emailTypeOptions').fadeOut 'fast', ->
for emailType in $('#emailTypes').val()
$("##{emailType}Options").fadeIn()
).call this
这是我的 .coffee
文件。但是,toggleEmailOptions
函数不在 jQuery ready
的范围内。我怎样才能使其在范围内?
(->
jQuery ->
globalThis = @
$('#emailTypes').change ->
globalThis.toggleEmailOptions()
toggleEmailOptions = ->
$('.emailTypeOptions').fadeOut 'fast', ->
for emailType in $('#emailTypes').val()
$("##{emailType}Options").fadeIn()
).call this
That's my .coffee
file. However, the toggleEmailOptions
function isn't in scope of the jQuery ready
. How can I make it in scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 http://jashkenas.github.com/coffee-script/
或者如果您使用的是 node.js ,则绑定到
exports
。对于你的例子,它变成:
From http://jashkenas.github.com/coffee-script/
Or bind to
exports
if you're using node.js .For your example, it becomes:
我认为你不需要换行,因为咖啡脚本已经做到了,这是我重写你的代码的方式:
I think you don't need to wrap because coffeescript already do it, here's how I would rewrite your code:
这里有几个问题。一是您似乎假设
@
/this
是 jQuery 回调中的全局对象 (window
)。但很容易看出事实并非如此:请记住,可以在库想要的任何上下文中调用回调。在本例中,
@
是文档
。并且document.toggleEmailOptions
不存在。此外,如果您希望
toggleEmailOptions
成为全局变量,则需要将其附加到window
(或@
/this
,因为@ 是文件最外层范围中的 window
)。这是因为当您只编写toggleEmailOptions = ...
时,CoffeeScript 使用var
声明将其范围限定在文件内。通过查看编译后的 JS 很容易看出这一点:var
始终位于其作用域的顶部。幸运的是,文件范围无论如何都是您想要的。所以基本上:不要想太多!你想要的是:
其余的保持原样。
There are a couple of problems here. One is that you seems to be assuming that
@
/this
is the global object (window
) from the jQuery callback. But it's easy to see that it isn't:Remember that callbacks can be called in whatever context the library wants. In this case,
@
isdocument
. Anddocument.toggleEmailOptions
doesn't exist.Further, if you want
toggleEmailOptions
to be a global, you need to attach it towindow
(or@
/this
, since@ is window
in the outermost scope of your file). That's because when you just writetoggleEmailOptions = ...
, CoffeeScript scopes it within the file using avar
declaration. It's easy to see this by looking at the compiled JS:var
s are always at the top of their scope. Fortunately, file scope is what you wanted anyway.So basically: Don't overthink it! What you want is:
and leave the rest as it is.