4 ms·
The main problem with JS "this" is that in a language where everything else is lexically scoped, "this" is dynamically scoped -- taking the value of whatever ob
by jashkenas 16y ago
The main problem with JS "this" is that in a language where everything else is lexically scoped, "this" is dynamically scoped -- taking the value of whatever object the function happens to be attached to at call time. To use a Ruby metaphor, imagine if "instance_eval" were the default way to call a method.
One of the main features that CoffeeScript adds to help with "this" issue is the bound function literal (the fat arrow). A regular function looks like this:
add = (num) -> this.value += num
And compiles into the regular JavaScript you'd expect:
var add;
add = function(num) {
return this.value += num;
};
However, if you define the function with a fat arrow instead:
add = (num) => this.value += num
You'll get a function bound to the current value of "this", and when you pass the function off to another object as a callback -- a DOM event handler, or success callback from an Ajax request -- the value of "this" doesn't change.
Here's perhaps a better example, from jQuery:
var self = this;
$(".row").bind("click", function() {
this.setText("Clicked!");
});
And in CoffeeScript, without the "self = this" bit:
$(".row").bind "click", =>
this.setText "Clicked!"