如何检测使用javascript调用的函数 [英] how to detect a function was called with javascript
问题描述
我有一个 javascript 函数.
I have a javascript function.
如何检查:
如果函数被调用(在
</head>
部分有这个函数),则不调用该函数
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
像 require_once
或 include_once
和 PHP
推荐答案
静态变量
以下是如何使用自调用函数创建静态(如在 C 中)变量以将静态变量存储在闭包中的方法.
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;
}
}
})()
抽象思想
这是一个函数,它返回一个只被调用一次的函数,这样我们就不必担心向每个函数添加样板代码.
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
这篇关于如何检测使用javascript调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!