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?

Mark
  • 981
  • 2
  • 13
  • 25
  • just move the `init` variable definition to `do` function, `isInitialized` doesn't currently close anything from the parent scope. – newtover Jan 21 '12 at 06:18

4 Answers4

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/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
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
   }
}
Tom
  • 43,583
  • 4
  • 41
  • 61
0

Try this:

function fn(){
  if (typeof fn.hasrun!='undefined'){return;}
  fn.hasrun=true;
  // do stuff
}
Mark Robbins
  • 2,427
  • 3
  • 24
  • 33
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

Community
  • 1
  • 1
Marc B
  • 356,200
  • 43
  • 426
  • 500