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 and inefficient. Instead, I use the following algorithm:
For instance methods, always call with the base object or with call/apply. Don't use `this` in methods that are to be called as static, so you can use variable shortcuts for those static methods, pass them around. // DONT DO THIS var StyleUtils = { HAS_COMPUTED_STYLE : (function() { /*...*/ return true; })(), getStyle : function(el, name) { // FAILED STRATEGY, `this` in static context. if(this.HAS_COMPUTED_STYLE) { return "worked"; } return "didn't work"; } }; That most JavaScript programmers like to bind every function says more about trends in JavaScript programming than about JavaScript. > 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. var o = { m : function(){ alert( this == o ); } }; o.m(); // true, o is base object var f = o.m; f(); // false. Calling f() results false because the base object is a declarative environment record (called VariableObject in ES3). And when that happens, the `this` value is either global object or null in ES5 in some cases. -- Garrett _______________________________________________ es-discuss mailing list es-discuss@mozilla.org https://mail.mozilla.org/listinfo/es-discuss