How can I pass "this" into setTimeout callback?
fiddle
code:
<button onclick="this.disabled=true; setTimeout(function(){this.disabled=false;},500);">click</button>
this
seems to refer to the window rather than the button. How can I pass the button object in so that I can re-enable it?
I'm aware of workarounds... I could give the button an ID and then grab it again, but I'm interested to know if I can somehow pass this
in.开发者_JS百科
this
is a defined by how a function is called.
foo.someFunc(); /* this is foo */
foo.bar.someFunc(); /* this is bar */
window.someFunc(); /* this is window */
someFunc(); /* this is window because window is the default */
setTimeout(foo.bar.someFunc, 500); /* this is window because you've passed a function and disassociated it from foo.bar */
If you want to pass it around between functions, you have to copy it to a different variable.
<button onclick="this.disabled=true; var that = this; setTimeout(function(){that.disabled=false;},500);">click</button>
You can explicitly set the context of a function by binding it.
<button onclick="
this.disabled=true;
setTimeout(
function(){this.disabled=false}.bind(this),
500)">click</button>
You'll notice that the disabling works, just the enabling doesn't. This is because this
isn't a local variable; it takes on its proper meaning when the event handler fires: no longer bound to the button.
Try this:
<button onclick="var self=this; self.disabled=true; setTimeout(function(){self.disabled=false;},500);">click</button>
BTW, try to avoid writing code inline like this. Write proper handlers for great victory:
// HTML:
<button id="myBtn">click</button>
// JS:
window.onload = function() {
document.getElementById('myBtn').addEventListener("click", function() {
var self = this;
self.disabled = true;
setTimeout(function() {
self.disabled = false;
}, 500);
}, false);
}
More verbose, yes, but ultimately far more maintainable.
jQuery makes it even easier:
$(function() {
$('#myBtn').click(function() {
var self = this;
self.disabled = true;
setTimeout(function() {
self.disabled = false;
}, 500);
});
});
精彩评论