简体   繁体   中英

Issues with executing setTimeout on a function - passing this as a parameter

Hi guys I have a function which accepts this as a parameter - ' this ' referring to the dom element which upon clicked should run a function. The thing is that I want this function to be called after a small delay however passing the variable term this doesn't work as when the function is executed ' this ' then doesn't refer to the object in passed in the parameter but to the window object.

How can I get this done?

You could capture this :

var t = this;
window.setTimeout(function() {
    // use the t variable here
}, 2000);

PrototypeJS adds the bind() method to Function.prototype . This method allows you to bind a function and arguments to the context of a particular object. Simply,

window.setTimeout((function() {
    alert(this);
}).bind(this), 2000);

The best part is that this method is now part of the ECMA-262 specification, which JavaScript is based upon, and native implementations are rolling out into modern browsers. PrototypeJS will only add this method if it's not already implemented.

I've set up an example script at http://jsfiddle.net/rLpbx/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM