0

JS-伙计们,我遇到了一个小测试脚本的问题。

我有这个JS:

var button = {
    lastClick: 0,
    nowTime: new Date().getTime(),
    go: function () {
        var diff = this.nowTime - this.lastClick; 
        if (diff < 3000) alert('Too fast:' + diff / 1000); 
        lastClick = this.nowTime;
    }.bind(this)
};

这个HTML:

<input type="button" value="Go"  onClick="button.go();" />

go-function 应该使用我的 -object 中的andnowTimelastClickbutton但它们是undefined。有谁能够帮我?

JS-小提琴

4

1 回答 1

3

那是因为this在你进行绑定时是未定义的(所以你绑定到window)。

你可以这样做 :

var button = {
    lastClick: 0,
    nowTime: new Date().getTime()
};
button.go = function () {
    var diff = this.nowTime - this.lastClick; 
    if (diff < 3000) alert('Too fast:' + diff / 1000); 
    this.lastClick = this.nowTime;
}.bind(button);

您还缺少一个this.before lastClick

另一种方法是使用闭包/工厂:

var button = (function(){
  var lastClick = 0;
  var nowTime = new Date().getTime();
  return {
    go: function () {
      var diff = nowTime - lastClick; 
      if (diff < 3000) alert('Too fast:' + diff / 1000); 
      lastClick = nowTime;
    }
  }
})();

不同之处(可能对您有利也可能没有)是按钮的内部状态隐藏在此版本中(这些字段通常被称为“私有”)。

如果您希望 nowTime 始终是当前时间,请不要存储它:

var button = (function(){
  var lastClick = 0;
  return {
    go: function () {
      var nowTime = new Date().getTime();
      var diff = nowTime - lastClick; 
      if (diff < 3000) alert('Too fast:' + diff / 1000); 
      lastClick = nowTime;
    }
  }
})();
于 2013-04-12T07:55:01.080 回答