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

时间:2016-08-08 03:10:33

标签: javascript

我想在第一次调用$ sudo apt-get install php5-mysqlnd 函数时运行这行代码,然后在第二次函数运行时运行它不应该运行

this.totalVote = this.totalVote - 1;

3 个答案:

答案 0 :(得分:0)

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

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 {

       }
  }

答案 1 :(得分:0)

如果您希望函数保留某个状态(例如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();




答案 2 :(得分:0)

我想你可以添加另一个变量来跟踪函数是否被调用?

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 {

   }
}
相关问题