Ian Jamieson
Ian Jamieson

Reputation: 4816

What is the best way to reference "this" in a CoffeeScript class in a function within a method?

Hopefully the question makes sense, the best way to explain would be to show you an example. I am creating a class in CoffeeScript and often use @ to represent "this" in JS, however, what is the best way to use it in the example below? At the moment I am storing @ in a local variable for that method, I was wondering if there was a better way

class app

constructor: ->
    # store @ or "this" in a new local var
    $this = @

    # do some stuff

    # Do some sort of jQuery stuff
    $(document).jquerystuff(->
        # do something that references this
        $this.anotherMethod()
    );

Upvotes: 0

Views: 275

Answers (1)

Matt Ball
Matt Ball

Reputation: 359816

Don't use $this as an alias for this in your CoffeeScript class. $foo is a common notation for saying "this variable refers to a jQuery object," but an arbitrary CoffeeScript class is not a jQuery.

Use =>, the fat arrow, instead of -> and you won't need to alias @ at all.

$(document).jquerystuff(=>
    @anotherMethod()
);

Alternately, if you do need to access the original jQuery- (or whatever-) provided this in the callback, and you care to follow Airbnb's JavaScript style guide, the naming conventions dictate that you use _this as the alias:

_this = @

$(document).jquerystuff(->
    _this.anotherMethod()
);

Upvotes: 6

Related Questions