如何使函数中的表达式仅在函数调用时第一次运行



当函数调用this.totalVote = this.totalVote - 1;时,我想第一次运行这行代码,之后当函数第二次运行时,它不应该运行

downVote(eve){
      this.totalVote = this.totalVote - 1;
      if(this.ristricted === this.totalVote){
              this.totalVote = this.totalVote - 1;
      }else {
       }
  }

设置一个全局变量来控制是否运行该行:

var downvoted = false;
downVote(eve){
      if(downvoted === false) {
        this.totalVote = this.totalVote - 1;
        downvoted = true;
      }
      if(this.ristricted === this.totalVote){
              this.totalVote = this.totalVote - 1;
      }else {
       }
  }

如果你想让函数保持某种状态(例如calledBeforecallCount属性(,你可以在函数本身添加一个属性:

function downVote(eve){
  if (!downVote.calledBefore) {
    downVote.calledBefore = true;
    // do one-time only stuff here:
    this.totalVote = this.totalVote - 1;
  }
  // do other stuff here:
  if(this.ristricted === this.totalVote){
     this.totalVote = this.totalVote - 1;
  }
}

或者,您可以将函数封装在闭包中,以私下保存状态:

var downVote = (function (){
  var calledBefore = false;
  return function downVote(eve) {
    if (!calledBefore) {
      calledBefore = true;
      // do one-time only stuff here:
      this.totalVote = this.totalVote - 1;
    }
    // do other stuff here:
    if(this.ristricted === this.totalVote){
       this.totalVote = this.totalVote - 1;
    }
  }
})();

后者的演示:

    var downVote = (function (){
      var calledBefore = false;
      return function downVote(eve) {
        if (!calledBefore) {
          calledBefore = true;
          // do one-time only stuff here:
          console.log("First call");
        }
        // do other stuff here:
        console.log("Called");
      }
    })();
    downVote();
    downVote();
    downVote();

如果函数已经被调用,我想您可以添加另一个变量来跟踪吗?

this.downVoteCalled = false;
downVote(eve){
  if(!this.downVoteCalled){
    this.totalVote = this.totalVote - 1;
    this.downVoteCalled = true; 
  }
  if(this.ristricted === this.totalVote){
          this.totalVote = this.totalVote - 1;
  }else {
   }
}

最新更新