Function.apply in connection source code

Reading the connect source code , I came across the following lines. I want to know why he is using Function.apply

.

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

      

As I understand it, Function.apply is used in cases where you want to call a function with a different value this

. Since the example above is server.listen

this

already server

, is it enough to just write the following?

app.listen = function(){
  var server = http.createServer(this);
  return server.listen(arguments);
};

      

+3


source to share


1 answer


.apply(thisArg, argsArray)

takes two arguments, which you can see here . The first argument (which sounds like you already know) is the value this

to call the function. The second argument is a massive object containing all the arguments to be passed to the function. This second argument is why it is being used here, so that it can call the function with exactly the same arguments that were passed to the first function app.listen()

.

This is a common use for "passing" all arguments from one function to another without knowing what the arguments actually are. Since the object arguments

is a massive data structure, it matches the second argument .apply()

, which expects the array-like object to be an argument list.




server.listen(arguments);

won't work because it will call .listen()

, but it will pass a single argument to the function, which is an array of arguments. This is not a function signature server.listen()

. It needs each argument passed separately, not a list. .apply()

serves to correct this. It takes an array of arguments and passes them as separate arguments to the called function.

server.listen(...)

Complicated by the fact that it has four different possible sets of arguments that can be passed to it. Usage .apply()

allows the forwarding code to be completely independent of which arguments were actually passed, as it just passes exactly what was actually passed without knowing anything about it.

+4


source







All Articles