How do I refer to actual 'this' inside CoffeeScript fat-arrow callback?

后端 未结 1 774
情深已故
情深已故 2021-01-15 08:19

The title says it all. When I use the fat-arrow in CoffeeScript, it stores this first before calling the function. For example:

class myClass
           


        
相关标签:
1条回答
  • 2021-01-15 08:30

    You can achieve your goal in at least three ways. The 1st one would be:

    class myClass
        constructor: ->
            element = $ "#id"
            element.click =>
                @myMethod(element.value)
                return
            return
    
        myMethod: (c) ->
            window.console.log(c)
            return
    

    And the 2nd:

    class myClass
        constructor: ->
            element = $ "#id"
            myMethodCallback = (c) => @myMethod(c)
            element.click ->
                myMethodCallback(@value)
                return
            return
    
        myMethod: (c) ->
            window.console.log(c)
            return
    

    The 3rd one is as showed below. I'm not sure about jQuery API usage though, so better check on appropriate docs page.

    class myClass
        constructor: ->
            element = $ "#id"
            element.click (event) =>
                @myMethod(event.target.value)
                return
            return
    
        myMethod: (c) ->
            window.console.log(c)
            return
    

    I would prefer the 1st way as it seems to be more straightforward. This or the other but you need to decide 'which this' you would like to have in scope of the element.click callback. It's not possible to access two 'thises' at the same time.

    By the way. All those return statements seems unnecessary. The shortest working solution would look like:

    class myClass
        constructor: ->
            element = $ "#id"
            element.click => @myMethod(element.value)
    
        myMethod: (c) -> window.console.log(c)
    
    0 讨论(0)
提交回复
热议问题