4

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);
}
0

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the link to your question was very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.