0

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()
    );
Ian Jamieson
  • 4,376
  • 2
  • 35
  • 55

1 Answers1

6

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()
);
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710