[Javascript] How to pass an object to a function

liorean liorean at f2o.org
Fri May 14 19:38:37 CDT 2004


Mike Dougherty wrote:
> What should this be to make this work:  (wait 1 second of hovering 
> before firing a method)
 
> <span id='menuitem1' onMouseOver="miOver(this)">hover here</span>
 
> function miOver(obj) {
>   timerid = setTimeout("doSomething(" + obj + ")", 1000);
>   }

The problem here is that the argument is a string, and that everything executed by timeouts or intervals is run in the global scope. So, neither a local variable nor the this keyword can be sent as an argument to a function run by the timeout or interval. However, you can use closures for this. An example of easy closure creation if you want to capture local variables:

function miOver(obj){
    var
        timer=setTimeout(function(){doSomething(obj)},1000);
}

> function doSomething(obj) {
>   alert(obj.id)
>   }

And I can as well give two examples of how to achieve the same effect for the this keyword. Essentially you need to make the this keyword a local variable in some way, in this first case using the same way as above:

elm.onmouseover=function(e){
    var
        obj=this,
        timer=setTimeout(function(){doSomething(obj)},1000);
}

Or a little more cumbersome, but maybe sometimes a little more understandable for someone not used to the quirks of the language:

function callFunctionWithArgument(fn, arg){
    return function(){
        fn(arg);
    };
}

elm.onmouseover=function(e){
    var
        timer=setTimeout(callFunctionWithArgument(doSomething, this),1000);
}
-- 
David "liorean" Andersson

ViewStyles, ViewScripts, SwitchStyles and GraphicsInfo bookmarklets:
<http://liorean.web-graphics.com/>
Hangouts:
<http://codingforums.com/> <http://yourmusicforums.com/>



More information about the Javascript mailing list