There are many approaches.
You need to put a flag somewhere. In the absence of anything else, you can put it on a window , but use a name that is unlikely to conflict with anything else.
Then JavaScript is pretty simple:
if (!window.myUniqueNameFlag) { window.myUniqueNameFlag = true;
But then again, putting things on a window not ideal if you can avoid it, although this is a very common practice. (Any function or variable declared in the global scope is a window property.)
If your function is already declared in the global scope (and therefore already occupies a character), you can do this to avoid creating a second character. Instead:
function foo() {
Do it:
var foo = (function() { var flag = flase; function foo() { if (!flag) { flag = true;
It looks complicated, but it is not: we define an anonymous function in which we define a variable and a nested function, then return a reference to the nested function and assign it to the external variable foo . You can call foo and you will get a nested function. The nested function has a permanent reference to the flag variable, because it closes the variable , but no one sees it. It is completely closed.
A third option is to simply use the flag for the function object itself:
function foo() { if (!foo.flag) { foo.flag = true;
Functions are just objects with the ability to be called, so you can add properties to them.
TJ Crowder Nov 16 '10 at 12:59 2010-11-16 12:59
source share