tags:

views:

153

answers:

1

I ran across this snippet in an internal web site, but I'm having trouble understanding it:

function safeWrap(f) {
  return function() {
    setTimeout.apply(window, [f, 0].concat([].slice.call(arguments)));
  };
}

Later on, it's used like this:

// Set click handler.
(...).click(safeWrap(function() { ... } ));

What is this meant to do?

+11  A: 

safeWrap returns a function that sets a timeout of 0ms when called (click event fired).

If the safeWrap function is passed more arguments than f, it will add these to the argument list of function f.

Thats just interpretation of the code provided. So I can't tell what it really is meant to do... Where is this code used, for example?

Ronald
Thanks for your answer, Ronald. Can you elaborate a bit on why ".call" is invoked on ".slice"? I'm most confused about this part.
Kyle Kaitan
@Kyle, [].slice.call(arguments) is used to transform the arguments object into an array object. The arguments object is said to be an array-like object (it has a length property and some properties use number for their names). Calling slice in the context of arguments makes the return value to be an array that contains those numbered properties in arguments.
Ionuț G. Stan
The "call" method runs the function with the specified arguments, so you get its return value (an array) and not the function reference.
Ronald