1

I'm trying to create javascript closure that will tell me if the function has already been run:

This is what I have so far:

function do()
{
   var isInitialized = function()
   {
     var init = false;

     if (init == false)
     {
       init = true;
       return false;
     }

     return init;
   }

   if (!isInitialized())
   {
     // do stuff
   }
}

My function isInitialized always evaluates to true. I'm like 90% sure I'm not setting the internal variable correctly. How do I fix my code?

1
  • just move the init variable definition to do function, isInitialized doesn't currently close anything from the parent scope. Commented Jan 21, 2012 at 6:18

4 Answers 4

2

First of all, you can't use do as your function name as that's a keyword.

Secondly, you can attach properties right to your function so you don't need a closure or anything like this:

function f() {
    if(f.initialized)
        return;
    f.initialized = true;
    console.log('Doing things.');
}
f();
f();

That will give you just one "Doing things." in the console.

Demo (run with your JavaScript console open): http://jsfiddle.net/ambiguous/QK27D/

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

Comments

1

Functions are objects in JavaScript so they can be assigned properties which provides a convenient mechanism for achieving what you want to do:

function doit() {
   if (typeof doit.isInitialized === "undefined") {
     doit.isInitialized = true;
     // do stuff
   }
}

8 Comments

You'd have to change the do to something else as do is a keyword.
I thought that but was just copying Mark's naming.
Thanks, I ended up using this. I didn't think to hard about the method name when I was writing my question.
I know this answer is 9 months old, but hopefully I'll get an answer: Why do you use doit.isInitialized and not this.isInitialized? Thanks.
@pilau: because if you just say ‘doit()‘, then ‘this‘ inside the function will be ‘window‘ or the local equivalent of the global namespace.
|
0

Try this:

function fn(){
  if (typeof fn.hasrun!='undefined'){return;}
  fn.hasrun=true;
  // do stuff
}

Comments

0

Every time you call isinitialized, it'll reset all the variables to default, so init will ALWAYS start out false. The values set afterwards are NOT carried over to the next time isInitialiazed is called.

What you want is a 'static' variable, which JS doesn't directly support, but can be simulated as per this answer: Static variables in JavaScript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.