Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect a function was called with javascript

Tags:

javascript

aop

I have a javascript function.

How to check:

  • if function was called ( in <head></head> section have this function), then not to call the function

  • if function was not called ( in <head></head> section haven't this function), then call the function

like require_once or include_once with PHP

like image 662
Chameron Avatar asked Jul 26 '10 04:07

Chameron


People also ask

What happens when you call a function in JavaScript?

Invoking a JavaScript Function The code inside a function is not executed when the function is defined. The code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function".

What is function () () in JavaScript?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.


1 Answers

Static variables

Here's how to create static (like in C) variables using self calling functions to store your static variables in a closure.

var myFun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I've been called");
      called = true;
    }
  }
})()

Abstract the idea

Here's a function that returns a function that only gets called once, this way we don't have to worry about adding boiler plate code to every function.

function makeSingleCallFun(fun) {
  var called = false;
  return function() {
    if (!called) {
      called = true;
      return fun.apply(this, arguments);
    }
  }
}

var myFun = makeSingleCallFun(function() {
  console.log("I've been called");
});

myFun(); // logs I've been called
myFun(); // Does nothing
like image 178
Juan Mendes Avatar answered Oct 03 '22 17:10

Juan Mendes