views:

515

answers:

3

Hi,

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!

A: 

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
That wouldn't work because that's not the function I'm trying to attach a variable to. Thanks.
Ivan
+1  A: 

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
Works like a charm, thanks!
Ivan
+1  A: 

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
I was tempted to use this, but it's kind of confusing for my brain. Thanks anyway.
Ivan