简体   繁体   中英

Javascript - Pass a function with arguments as an argument

I'm cleaning up some script errors and have a delicate dilemma.

Consider this line of code:

Session.Timer = window.setTimeout("TimeoutHandler(Session)", 1000);

This will not work because when the Timeout tries to execute TimeoutHandler(Session) it will not know what the Session variable is (out of scope).

Is there a way to get the Session "value" translated to a string or number so it will be executed correctly?

Use a closure (using an anonymous function) instead of a string, it will keep a reference to Session for you.

Session.Timer = window.setTimeout(function() { TimeoutHandler(Session); }, 1000);

If you're unfamiliar with closures, here's a brief introduction .

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