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
- 函数应该使用nowTime
- 对象中的lastClick
和button
值,但它们未定义。有人能帮助我吗?
答案 0 :(得分: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.
之前也错过了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;
}
}
})();