[英]How to call function only once?
How can I call the function only for once? 我怎么只能调用一次函数?
var myFunction = function () {
alert("calling function only for once");
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert // if I call multiple times this should not be called
Try this: 尝试这个:
var myFunction = function () {
alert("calling function only for once");
myFunction = function(){
return false;
}
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert
在运行函数时将一些goobal变量存储为一个标志,并在函数启动时检查该变量。
set a flag, and call according to that flag: 设置一个标志,并根据该标志进行调用:
var IsAlreadyCalled=false;
var myFunction = function () {
if(!IsAlreadyCalled){
alert("calling function only for once");
IsAlreadyCalled = true;
}
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert
In your very odd scenario , the easiest way is to set a boolean: 在非常奇怪的情况下,最简单的方法是设置一个布尔值:
var run = true,
myFunction = function(){
if(run){
alert('calling function only for once');
run = false;
} else {
return false;
}
};
myFunction(); // will run
myFunction(); // won't run
That way later on if you need to "reactivate" it you can just set the boolean back to true and call it again. 这样以后,如果您需要“重新激活”它,就可以将布尔值设置回true并再次调用它。
run = true;
myFunction(); // will run again
Other suggestions of using a flag are fine, but I would build it as a function decorator, that you can apply to any function. 使用标记的其他建议很好,但是我会将其构建为函数装饰器,可以将其应用于任何函数。 You avoid global variables this way, and your code becomes more readable and reusable:
您可以通过这种方式避免使用全局变量,并且代码变得更具可读性和可重用性:
// Takes a function and returns a function
// that executes only once
function once(f) {
var flag;
return function() {
if (!flag) {
flag = true;
return f.apply(this, arguments);
}
};
}
var fn = once(function() {
console.log('logged!');
});
fn(); // logged!
fn();
fn();
Demo: http://jsbin.com/povu/1/edit 演示: http : //jsbin.com/povu/1/edit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.