views:

230

answers:

1

I sort of understand closures in javascript, but what I'm not sure about is how it treats nested functions. For example:

var a = function(o) {
    o.someFunction(function(x) {
        // do stuff
    });
}

I know a new closure is created everytime I call function a, but does that closure also include a new instance of the anonymous function passed to someFunction? Would it better if I did the ff instead:

var b = function(x) { /* do stuff */ }
var a = function(o) {
    o.someFunction(b);
}
+2  A: 

In your first example, every time that a is called, an anonymous function is defined and passed to someFunction(). This is more expensive than what you've got in the second example, which is the more efficient method, since the function (now called b) is only being defined once.

I asked a question similar to this a few months back: it might help you as well. http://stackoverflow.com/questions/80802/does-use-of-anonymous-functions-affect-performance

nickf
Thanks, the link to your question was very helpful.
jtjin