views:

45

answers:

2

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?

+2  A: 

You could capture this:

var t = this;
window.setTimeout(function() {
    // use the t variable here
}, 2000);
Darin Dimitrov
+2  A: 

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/.

Andy E
I'm getting an error here in firebug - my function is executing ignoring the timeout and firebug states its a useless settimeoutcall insisting I put quotes around the code :(
Ali
@Ali: that seems like an odd error. You should update your question with the code you have, I'll take a look at it and see what the problem is.
Andy E