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.
@dfkaye, I'm aware of
e.target
ande.srcElement
, but I still think thatthis
shouldn't be treated magically, as@
is.Using the
=>
syntax, you lose the ability to access the actualthis
in the closure. There might be cases where one needs to access the closure, right?I realize that this is trivial, and a workaround (or the proper way, depending on how you see it) is one extra line of code (or a few more characters, if it's a DOM event callback), but why does CoffeeScript bother with the
=>
syntax when you can only use it sometimes?