-1

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?

JS-Fiddle

asked Apr 12, 2013 at 7:53

1 Answer 1

2

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;
 }
 }
})();
answered Apr 12, 2013 at 7:55
Sign up to request clarification or add additional context in comments.

5 Comments

It's not necessary to separate the definitions of 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.
@MaxArt bind is necessary if you want to do, for example setTimeout(button.go, 100);.
Seems to work but now lastClick is equal to nowTime on every click. But nowTime should use getTime() fiddle.jshell.net/8u4Du/5
@alexP You want nowTime to always be new Date().getTime() ? So why store it ?
Good question @dystroy :-) I'll use your last suggestion. Thanks a lot.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.