Skip to content

Instantly share code, notes, and snippets.

@silasjmatson
Last active December 31, 2015 19:09
Show Gist options
  • Save silasjmatson/8031508 to your computer and use it in GitHub Desktop.
Save silasjmatson/8031508 to your computer and use it in GitHub Desktop.

Given the following CoffeeScript class:

class Foo

  constructor: ()->
    @bar()

  bar: ->
    $("body").on "click", (e)=>
      @baz(this)

  baz: (something)->
    console.assert(something == $("body"))

The following Javascript is produced:

(function() {
  var Foo;

  Foo = (function() {
    function Foo() {
      this.bar();
    }

    Foo.prototype.bar = function() {
      var _this = this;
      return $("body").on("click", function(e) {
        // Replaces both @ and this with _this
        return _this.baz(_this);
      });
    };

    Foo.prototype.baz = function(something) {
      return console.assert(something === $("body"));
    };

    return Foo;

  })();

}).call(this);

Shouldn't Coffeescript only replace @ with _this inside the callback? I'd like for this to be explicit and never treated magically, as is @.

It would certainly make behavior easier to understand.

@jamonholmgren
Copy link

That's a great point, @dfkaye. You're correct that e.target || e.srcElement would be more explicit and avoid this whole ambiguity altogether. In fact, using this is probably an anti-pattern to start with, despite jQuery's reliance on it.

I think the => syntax should only be used on very simple methods that do not need to refer to the child enclosure.

@silasjmatson
Copy link
Author

I think the only two places I've been using => are event callbacks and ajax callbacks.

@jamonholmgren
Copy link

Should make it relatively easy then! :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment