Coffeescript 类和范围以及粗细箭头 [英] Coffeescript classes and scope and fat and thin arrows
问题描述
在咖啡脚本类的粗箭头函数中,如何访问该类的范围以及函数?
In a fat arrowed function of a coffeescript class, how can I access the scope of the class as well as the function?
例子:
class Example
foo: ->
$('.element').each => # or ->
@bar($(this)) # I want to access 'bar' as well as the jquery element
bar: (element) ->
element.hide()
所以在这个例子中,如果我使用 =>,那么 @ 指的是类的 this,但 'this' 是错误的,而如果我对 each 使用 ->,那么 'this' 是范围正确,但是如何引用类函数栏?
So in this example, if I use a => then the @ refers to the this of the class but the 'this' is then wrong, whereas if I use a -> for the each, then the 'this' is correctly scoped but but then how do I reference the class function bar?
谢谢!
推荐答案
这是因为在 CoffeeScript 中 @
是 this
的别名,即当你将 .coffee 编译为 .js @
将被替换为 this
.
That's because in CoffeeScript @
is an alias for this
i.e. when you compile your .coffee to .js @
will be replaced with this
.
如果 Example::bar
很丑,我认为没有更漂亮"的解决方案.
If Example::bar
is ugly, I don't think there are 'prettier' solutions.
您可以在调用 .each
之前存储对 this
的引用:
You can store a reference to this
before calling .each
:
class Example
foo: ->
self = @
$('.element').each ->
self.bar($(this)) # or self.bar($(@))
bar: (element) ->
element.hide()
这篇关于Coffeescript 类和范围以及粗细箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!