Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

aop - how to detect a function was called with javascript

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...