Variables and closure scope with anonymous functions

Whenever the anonymous function is called with the a parameter passed to it, this essentially packs up everything with-in the anonymous function and if another call to the subscribed function is called before the first anonymous function gets called back from the database or ajax call, that will not affect the previous anonymous function and the current anonymous function that is being called will just create a new closure and all data for each new anonymous closure will not affect the next closure or the previous closure?

       this.subscribe.call(this, e.horizontaladded, function (a, fn) {

            if (!a.extra.owner.id) { return; };

       (function (a) {


                dataBase.insert(
                    dbPart(
                    ['horizontal?a=', a.extra.owner.instanceName, '&id=', a.extra.owner.id].join(''),
                    a.target
                    ),
                    dbCB(success, error)
                );


                function success(data, status) {

                    if (status === 'error') { return; };

                     console.log('Horizontal Added');


                    a.target.id = data.id,
                    a.target.HTML().addClass('alum_' + data.id),
                    a.target.finish.id = data.finishID,
                    a.target.size.id = data.sizeID,
                    a.target.siteLine.id = data.sitelineID;


            }(a));

   }, true);

In other words for each call that is called to the e.horizontaladded that I'm subscribed to each new anonymous function is invoked and is closed up with all it's own person data and garbage collection cleans up all the closures?

So if this function that I am subscribed to, if 30 horizontaladded calls are made and 30 closures are created, do the closures clean up themselves when they database success is called back?

Upvotes: 0

Views: 51

Answers (1)

jfriend00
jfriend00

Reputation: 707426

A closure is cleaned up by the garbage collector when there is no code that could possibly reach any of the variables inside the closure.

Really a closure works no differently in the garbage collector than any other object in javascript. When nobody has a reference to anything in it, then the garbage collector is free to clean it up.

In your specific example, your immediately invoked function expression creates a closure that will last as long as any other code has a reference to something in the closure. So, when the database.insert() function starts executing, it has a reference to your success() function and that keeps the closure alive. When it finishes and calls the success() function, it will presumably clear its reference to the success() function after calling it, thus freeing that reference to something inside the closure. If the garbage collector then finds no other references to anything in that closure, it will then free the closure.

Upvotes: 1

Related Questions