本文介绍了Coffeescript类和范围,脂肪和细箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在coffeescript类的胖箭头函数中,如何访问类的范围以及函数?



示例:

  class示例
foo: - >
$('。element')。each => #or - >
@bar($(this))#我想访问'bar'以及jquery元素
bar:(element) - >
element.hide()

所以在这个例子中,如果我使用a => @指的是类的this,但是'this'然后是错误的,而如果我使用 - >为每个,那么'this'是正确的范围,但但是如何引用类函数bar? / p>

谢谢!

解决方案

这是因为在CoffeeScript @ 是这个的别名,即当您将.coffee编译为.js @ 将替换为 this 。



如果 Example :: bar 是丑陋的,我不认为有更漂亮的解决方案。



你可以存储一个引用 this 之前调用 .each :

  b foo:> 
self = @
$('。element')。each - >
self.bar($(this))#或self.bar($(@))
bar:(element) - >
element.hide()


In a fat arrowed function of a coffeescript class, how can I access the scope of the class as well as the function?

Example:

class Example
  foo: ->
    $('.element').each =>  # or ->
      @bar($(this))        # I want to access 'bar' as well as the jquery element
  bar: (element) ->
    element.hide()

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?

Thanks!

解决方案

That's because in CoffeeScript @ is an alias for this i.e. when you compile your .coffee to .js @ will be replaced with this.

If Example::bar is ugly, I don't think there are 'prettier' solutions.

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类和范围,脂肪和细箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 02:55
查看更多