Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested function memory usage in javascript

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);
}
like image 242
jtjin Avatar asked Oct 30 '25 23:10

jtjin


1 Answers

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. Does use of anonymous functions affect performance?

like image 62
nickf Avatar answered Nov 01 '25 11:11

nickf