May 29, 2008

Javascript Tip - Using setTimeout with prototype object methods

This is a little esoteric but I thought I should share it as it took me a while to find a solution.

I use prototype as my framework of preference for building web applications. Recently I've been refactoring code I wrote for Bossa Live to make it more unobtrusive. Moving functionality from the HTML into prototype classes residing in included JavaScript files...

Anyway, the problem I came across is to do with using the JavaScript setTimeout function in prototype class methods. As is usual with this function the problem is scope. How do you execute the timeout function in the context of the calling object (so you can use object members). There are lots of solutions out there using closures etc but I figured there had to be an easier way.

The answer is with prototype's bind function of course! Syntax is below:

Note that you can pass the function you are binding as many arguments as you want. Just place them after the 'this' argument to bind (in the example above I only have one argument)

Posted by Barry at May 29, 2008 2:08 PM | TrackBack


This was exactly what I needed. Thanks a lot, it works very well! :)

Thank you!

Leave a comment