views:

55

answers:

1

I have a rather large set of javascript functions that I am working on refactoring into a set of classes using Prototype.

I was wondering if there was a way I could make binding anonymous functions to the class simpler? I keep forgetting to add the bind this at the end. Or is this just the way it is done all the time?

 var arr = this.getSomeArray();
 arr.each(function(t) {
     t.update(val);
     this.updateJSValue(t);
 }.bind(this));
+1  A: 

Your options are basically to call some function (bind, addMethods or another function you write) or use a local variable rather than this:

var self=this;
arr.each(function(t) {
     t.update(val);
     self.updateJSValue(t);
});

If you've a large number of functions, the local variable requires the least typing For just a few functions, there isn't too much difference.

function ThingMixin(self) {
    self.foo = function(arr) {
        arr.each(function(t) {
             t.update(val);
             self.updateJSValue(t);
        });
    };
    ...
};
...
ThingMixin(Ralph.prototype);

// or an anonymous function:
(function (self){
    self.foo = function(arr) {
        arr.each(function(t) {
             t.update(val);
             self.updateJSValue(t);
        });
    };
    ...
})(Ralph.prototype);
outis
is there any kind of performance increase/decrease with using the local variable? Most of the places where these are happening are in double for loops.
Casey
I'd expect memory usage to increase slightly, as the variables will live longer due to closures, but impact on performance should be negligible. Note that `bind` most likely makes use of a local variable.
outis
This comment has more to do with correctness than performance, but if you want to bind to the same object for each iteration, set `self` outside the loop and the performance impact would be unnoticeable; if you want to bind to a different object, declare `self` inside the loop block.
outis