Static variables in anonymous function

I am trying to emulate static variables in a JavaScript function with the following purpose:

$.fn.collapsible = function() {
  triggers = $(this).children('.collapse-trigger');
  jQuery.each(triggers, function() {
    $(this).click(function() {
      collapse = $(this).parent().find('.collapse');
    })
  })
}

How to save the object "collapse" so that it is not "found" with every call? I know that with the help of these functions I could do something like "someFunction.myvar = collapse", but what about anonymous functions like this?

Thanks!

+5
source share
4 answers

You can save your variable in a function using functioName.myVar = valueor arguments.callee.myVar = valueif you do not have the current function name.

arguments.callee - The current function you are in.

+11
source

, .

:

var myAnonymousFunction = (function(){
    var myFirstStatic = $("#anElement");
    var anotherStatic = true;
    return function(param1,param2) {
        // myFirstStatic is in scope
        // anotherStatic also
    }
})();

, , .

+8

, .

, , , .

mything.prototype.mymethod = function myKindOfFakeName() {
    myKindOfFakeName.called = true;
}
+1

, $.fn.collapsible , , $.fn.collapsible.myvar.

0