Reputation: 3765
JS-folks, I've got a problem with a little test-script.
I've got this 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)
};
And this HTML:
<input type="button" value="Go" onClick="button.go();" />
The go
-function should use the nowTime
and lastClick
values from my button
-object but they are undefined. Can anybody help me?
Upvotes: -1
Views: 63
Reputation: 382150
That's because this
is undefined when you make the binding (so you're binding to window
).
You can do this :
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);
You were also missing a this.
before lastClick
.
An alternative is to use a closure/factory :
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;
}
}
})();
A difference (which may or not be a benefit for you) is that the internal state of the button is hidden in this version (the fields are usually said to be "private").
If you want nowTime to always be the current time, don't store it :
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;
}
}
})();
Upvotes: 2