A project I’ve been working on has called for CoffeeScript so I’ve been diving into it. One quirk that happens with JavaScript is the scope of variables bound to the function() enclosing them. So what’s wrong with this?
class FooFoo
constructor: ->
@foo = 1
@some_fn()
some_fn: ->
$('#some-button').click (ev) ->
@foo += 1
That interior @foo inside some_fn() is going to have the wrong this when it compiles out:
var FooFoo;
FooFoo = (function() {
FooFoo.name = 'FooFoo';
function FooFoo() {
this.foo = 1;
this.some_fn();
}
FooFoo.prototype.some_fn = function() {
return $('#some-button').click(function(ev) {
return this.foo += 1;
});
};
return FooFoo;
})();
So it’s the => fat arrow (hashrocket in Ruby terms) to the rescue. It creates a function-scoped _this and does the right thing inside now:
var FooFoo;
FooFoo = (function() {
FooFoo.name = 'FooFoo';
function FooFoo() {
this.foo = 1;
this.some_fn();
}
FooFoo.prototype.some_fn = function() {
var _this = this;
return $('#some-button').click(function(ev) {
return _this.foo += 1;
});
};
return FooFoo;
})();
Ah, much better.
