开发者

Javascript closures in firebug

so...I'm trying to learn this new thing called closures... new for me.... Out of Academic interest:

DESCRIPTION

When I create global variable or function in JS - I can easily see them in firebug's DOM tab (they attached to Window object). When I create objects - the same story. I can see objects in Firebug DOM's tab.

开发者_如何学运维

QUESTION:

How about variables and functions inside of closures - where are they attached to? I don't see these closure private variables in Firebug's DOM tab. Is that the way it's supposed to work?

(function () {
    var test1 = 'test'; //do't se it in DOM
    function test2(){  //do't see it in DOM
    }
}());


The DOM tab only shows the variables and functions defined globally. It never shows any local variables or functions.

Closures mean that a local variable used by a local function will remain in memory for as long as the function itself remains in memory, instead of being destroyed right away. Since it's all about being local, they don't show up in the list of global variables in the DOM tab.

Consider the following:

  var increment = (function(){
    var i = 0;
    return function() { 
      return i++;
    }
  })();

  increment(); // should return 0
  increment(); // should return 1

You can still see the value of i, but it's only available from within the closure, so you need to place a breakpoint on the return i++; line and look for i in the 'local variables' section of the Script tab.


Well that's old story. Newer versions of Firebug (from 1.11.2) can show closure variables too. Using command line enter the following.

closure.%variable

Or you can use the DOM watch panels to show the closure variables by clicking the arrow right next inside DOM tab and checking the show closure option.

More details here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜