7

I'm trying to mimic static variables on 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 do I save the "collapse" object so it doesn't have to be "found" on each call? I know that with named functions I could do something like "someFunction.myvar = collapse", but how about anonymous functions like this one?

Thanks!

Ivan
  • 97,549
  • 17
  • 50
  • 58

4 Answers4

13

You can save your variable in the function, using either functioName.myVar = value or arguments.callee.myVar = value if you don't have the current function name.

arguments.callee is the current function you are in.

Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
10

For anonymous function you could use a function that returns a function.

For instance:

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

Should work like a charm and you're assured initialisation code for statics is only executed once.

Julian Aubourg
  • 11,346
  • 1
  • 29
  • 29
2

It seems that a better answer to this question is found elsewhere on Stack Overflow.

In short, you can actually give anonymous functions names without polluting the namespace, yet still allow self-referencing.

mything.prototype.mymethod = function myKindOfFakeName() {
    myKindOfFakeName.called = true;
}
Community
  • 1
  • 1
Chuck
  • 1,062
  • 12
  • 28
0

As long as you're assigning the function to a variable like that, you should be able to access it as $.fn.collapsible, and thus assign variables as $.fn.collapsible.myvar.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • That wouldn't work because that's not the function I'm trying to attach a variable to. Thanks. – Ivan Mar 16 '09 at 23:43