Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in an anonymous function

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!

like image 306
Ivan Avatar asked Mar 15 '09 02:03

Ivan


3 Answers

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.

like image 108
Vincent Robert Avatar answered Nov 17 '22 00:11

Vincent Robert


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.

like image 43
Julian Aubourg Avatar answered Nov 17 '22 01:11

Julian Aubourg


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;
}
like image 2
Chuck Avatar answered Nov 17 '22 02:11

Chuck