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?
1 Answer 1
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;
}
}
})();
5 Comments
button and button.go, is it? Also, bind isn't necessary as well here. I wonder if alexP isn't referring to something else with that this as the argument of bind.setTimeout(button.go, 100);.lastClick is equal to nowTime on every click. But nowTime should use getTime() fiddle.jshell.net/8u4Du/5