javascript - Function.apply in connect's source code -


this question has answer here:

reading connect's source code, came across following lines. want know why it's using function.apply.

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

as understand, function.apply used in cases want call function different this value. since server.listen's this server in above example, isn't sufficient write following?

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

.apply(thisarg, argsarray) takes 2 arguments can see described here. first argument (which sounds know) this value function call. second argument array-like object contains arguments passed function. second argument why being used here can call function same arguments passed first function app.listen().

this common usage "forwarding" arguments 1 function without having know arguments are. since arguments object array-like data structure, fits second argument of .apply() expects array-like object list of arguments.


server.listen(arguments); not work because call .listen(), passing single argument function array-like list of arguments. not function signature of server.listen(). needs each argument passed separately, not passed in list. .apply() serves purpose of fixing that. takes array-like list of arguments , passes them individual arguments called function.

server.listen(...) further complicated fact has 4 different possible sets of arguments can passed it. use of .apply() allows forwarding code entirely independent of arguments passed forwards passed without having know it.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -