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

后端 未结 4 2148
野的像风
野的像风 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:35

    Usually, -> is fine.

    class Foo
      @static:  -> this
      instance: -> this
    
    alert Foo.static() == Foo # true
    
    obj = new Foo()
    alert obj.instance() == obj # true
    

    Note how the static method return the class object for this and the instance returns the instance object for this.

    What's happening is that the invocation syntax is providing the value of this. In this code:

    foo.bar()
    

    foo will be the context of the bar() function by default. So it just sorta works how you want. You only need the fat arrow when you call these function in some other way that does not use the dot syntax for invocation.

    # Pass in a function reference to be called later
    # Then later, its called without the dot syntax, causing `this` to be lost
    setTimeout foo.bar, 1000
    
    # Breaking off a function reference will lose it's `this` too.
    fn = foo.bar
    fn()
    

    In both of those cases, using a fat arrow to declare that function would allow those to work. But unless you are doing something odd, you usually don't need to.

    So use -> until you really need => and never use => by default.

提交回复
热议问题