News for hackers. Stuff that matters.
Re:Javascript: is 'this' a code smell? by Detrus on Thursday November 04, 2010 @10:17PM (#1871726)
The syntax is definitely awkward. But efforts like coffee-script http://jashkenas.github.com/coffee-script/ are here to alleviate some of these pain points.
Re:Javascript: is 'this' a code smell? by jashkenas on Thursday November 04, 2010 @10:35PM (#1871772)
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!"
Re:Javascript: is 'this' a code smell? by amadiver on Thursday November 04, 2010 @10:20PM (#1871732)
Unfortunately, CoffeeScript doesn't support implicit "this". I'm working on that problem, and I hope to share it soon.