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!

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What about an arrow function?
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.

Comments

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; } 

Comments

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.

1 Comment

That wouldn't work because that's not the function I'm trying to attach a variable to. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.