我有一个javascript函数.
如何检查:
如果<head></head>调用了函数(在具有此函数的部分中),则不调用该函数
如果未调用函数(在<head></head>部分中没有此函数),则调用该函数
喜欢require_once或include_once与PHP
Jua*_*des 30
两种选择:
静态变量以下是如何使用自调用函数在闭包中存储静态变量来创建静态(如在C中)变量.
var myFun = (function() {
var called = false;
return function() {
if (!called) {
console.log("I've been called");
called = true;
}
}
})()
Run Code Online (Sandbox Code Playgroud)
空功能替换在运行后将功能设置为空功能.
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 nothingRun Code Online (Sandbox Code Playgroud)
摘要这个想法这是一个返回一个只调用一次的函数的函数,这样我们就不用担心将锅炉板代码添加到每个函数中.
var myFun = (function() {
var called = false;
return function() {
if (!called) {
console.log("I've been called");
called = true;
}
}
})()
Run Code Online (Sandbox Code Playgroud)
Tör*_*bor 11
使用装饰图案.
// your function definition
function yourFunction() {}
// decorator
function callItOnce(fn) {
var called = false;
return function() {
if (!called) {
called = true;
return fn();
}
return;
}
}
yourFunction(); // it runs
yourFunction(); // it runs
yourFunction = callItOnce(yourFunction);
yourFunction(); // it runs
yourFunction(); // null
Run Code Online (Sandbox Code Playgroud)
该解决方案为实现目标提供了无副作用的方式.您不必修改原始功能.即使使用库函数它也很好用.您可以为装饰函数指定新名称以保留原始函数.
var myLibraryFunction = callItOnce(libraryFunction);
myLibraryFunction(); // it runs
myLibraryFunction(); // null
libraryFunction(); // it runs
Run Code Online (Sandbox Code Playgroud)
var called = false;
function blah() {
called = true;
}
if ( !called ) {
blah();
}
Run Code Online (Sandbox Code Playgroud)