On 4/11/11, Claus Reinke <claus.rei...@talk21.com> wrote:
> Like most Javascript programmers, I have tended to follow
> a simple rule for functions using 'this': eta-expand method
> selections, use .bind, or get into trouble.
>
That is unnecessary, inefficient, and adds clutter.

That most JavaScript programmers do that says more about trends in
JavaScript programming than it does about the language.

> Then I got curious about how method calls determine what
> object to pass as 'this': a method is a function selected from
> an object, and functions are first-class values, so, by the time
> they get called, how do we know where they came from?
>
The base object.

Follow these two rules to greatly reduce `this` reference confusion.

1. For instance methods (such as prototype methods), either qualify
the method call with the base object or use call/apply. For example,
var x = new X;
x.m(); // Qualified instance method
// DONT DO THIS
var m = x.m;
m();

2. For static methods, write them so that they never use `this`. For
example, here is an example of static method `getStyle` that violates
that rule and uses `this`:

// DONT DO THIS
var StyleUtils = {
  HAS_COMPUTED_STYLE : (function() { /*...*/})(),
  getStyle : function(el, name) {
    // Problem: Use of `this` in static method.
    if(this.HAS_COMPUTED_STYLE) {
    }
  }
};

By never using `this` in static methods, it can be assured that they
can be aliased with a variable and passed around, e.g. `var getStyle =
StyleUtils.getStyle`.
-- 
Garrett
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to