Unexpected behaviour when mixing setTimeout and .apply()
by Developer @ pebbl.co.uk on Sunday, 26 June 2011
Recently I came across this - presumably the side effect of security measures - but it seems that unlike other functions, you can't just override the "this" object on many of the native functions (i.e. setTimeout) in most modern browsers (using either the call or apply methods of the Function object).
Now you might ask why you would want to do that, and yes... I can't really give you an example if I'm honest (save for rather mental user-agent detection) - but the thing that I find strange is that whilst you can't set "this" to any of the standard variable types, you can set it to either "null" or "undefined". If I was to read through the actual source of the browsers, I'm sure I would find the reason for this... but I just found it odd logic. In my mind any change should either throw a security exception or not, but anyways.. just thought I'd mention it.
On the following link you should see some coloured squares - if you hover (and wait for the title text to appear) you'll see a description of what was tested and any error that was tripped. The green squares mean the setTimeout fired with it's this object set - the red means it failed / caused an exception. If you test different browsers you'll see that MacBook OSX {FF4/FF5, Safari5, Chrome(12.0.742.100)} all agree whereas MacBook OSX {Opera 10.10} allows the basic var types but nothing complex, and Dell Lattitude WinXP {IE8} doesn't even support the apply() method.
- Leave your comment • Category: Coding, JavaScript
- Share on Twitter, Facebook, Delicious, Digg, Reddit