仅调用一次

时间:2019-05-03 15:55:17

标签: javascript

有人可以帮助我进行故障排除吗?

var something = (function() {
  var executed = false;
  return function() {
    if (!executed) {
      executed = true;
      alert("Hi");
    }
  };
})(); //Removing the following calls the function does not execute with parenthesis

something(); //Happens
something(); //Nothing happens

我的方法:

var only = (function once() {
  alert("Kaixo");
  only = false;
})(); //That parenthesis calls the function

only(); //Calls the function 
only(); //Nothing happens

如果我的示例在原始示例之前运行,则会中断。 继续本主题:Function in javascript that can be called only once

3 个答案:

答案 0 :(得分:4)

您正在将only设置为函数返回的值,即undefined。即使您不直接调用它,也无法使用,因为无法调用false

您可以将功能设置为另一个没有任何作用的虚拟功能。

function only(){
   alert("Kaixo");
   only = function(){}
}

only(); //Calls the function 
only();

答案 1 :(得分:3)

此处onlyfunction,而不是boolean。因此,与其将其覆盖为false,而不是将其覆盖为空函数。参见:

var only = (function once() {
    alert("Kaixo");
    only = function () {};
}); // Don't call the function!

only(); // Calls the function 
only(); // Nothing happens

答案 2 :(得分:0)

var only = (function once() {
  var executed = false; // Inits the flag;
  return function() {
    if (!executed) {      
      executed = true; //Set the flag
      alert("Kaixo");
    }
}  

})(); //That parenthesis calls the function

only(); //Calls the function 
only(); //Nothing happens