CoffeeScript, When to use fat arrow (=>) over arrow (->) and vice versa

后端 未结 4 2135
野的像风
野的像风 2020-11-30 16:58

When building a class in CoffeeScript, should all the instance method be defined using the => (\"fat arrow\") operator and all the static methods being defin

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 17:53

    No, that's not the rule I would use.

    The major use-case I've found for the fat-arrow in defining methods is when you want to use a method as a callback and that method references instance fields:

    class A
      constructor: (@msg) ->
      thin: -> alert @msg
      fat:  => alert @msg
    
    x = new A("yo")
    x.thin() #alerts "yo"
    x.fat()  #alerts "yo"
    
    fn = (callback) -> callback()
    
    fn(x.thin) #alerts "undefined"
    fn(x.fat)  #alerts "yo"
    fn(-> x.thin()) #alerts "yo"
    

    As you see, you may run into problems passing a reference to an instance's method as a callback if you don't use the fat-arrow. This is because the fat-arrow binds the instance of the object to this whereas the thin-arrow doesn't, so thin-arrow methods called as callbacks as above can't access the instance's fields like @msg or call other instance methods. The last line there is a workaround for cases where the thin-arrow has been used.

提交回复
热议问题