Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a function has been called without setting global variable

Tags:

I am looking for a good technique to get away from what I am tempted to do: to set a global variable.

The first time someone runs a function by clicking a button it triggers an initial function to turn a few things into draggables. Later, if they click the button a second time I want to determine if the init function has been initialized, and if so to not call it again. I could easily do this by setting a global variable from the init function and then checking that variable from the click function, but I'm wondering how to do this without setting a global variable. I would really like an example of a way to do this.

like image 200
codelove Avatar asked Jul 02 '12 19:07

codelove


People also ask

How do you check if a function has been called?

You can log a message when the function is called using: Debug. Log("Function called!"); You can store a bool that starts as false and set it to true when you enter the function. You can then check this bool elsewhere in code to tell whether your function has been called.

How do I check if a global variable exists?

To check if a global variable exists in Python, use the in operator against the output of globals() function, which has a dictionary of a current global variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.

What are two reasons why you should not use global variables?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.


2 Answers

You could add a property to the function:

function init() {     init.called = true; }  init();  if(init.called) {     //stuff } 
like image 104
Levi Hackwith Avatar answered Oct 27 '22 11:10

Levi Hackwith


While @Levi's answer ought to work just fine, I would like to present another option. You would over write the init function to do nothing once it has been called.

var init = function () {    // do the initializing      init = function() {         return false;     } }; 

The function when called the first time will do the init. It will then immediately overwrite itself to return false the next time its called. The second time the function is called, the function body will only contain return false.

For more reading: http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/

like image 31
Amith George Avatar answered Oct 27 '22 11:10

Amith George