Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  64] [ 5]  / answers: 1 / hits: 48196  / 11 Years ago, mon, august 12, 2013, 12:00:00

Sometimes I see JavaScript that is written with an argument provided that already has a set value or is an object with methods. Take this jQuery example for instance:



$(.selector).children().each(function(i) {
console.log(i);
});


When logging i, you would get the value of whatever i is in that iteration when looking at the selectors children in the jQuery each method.



Take this Node.js example:



http.createServer(function(request, response) {
response.writeHead(200, {Content-Type: text/plain});
response.write(Hello World);
response.end();
}).listen(8888);


You can see here that request and response are being passed and they contain their own methods that can be acted on.



To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them.



My question is a multipart one:




  1. Where do these arguments come from?

  2. If these are just anon functions, how do they receive arguments that can be acted on like other functions?

  3. How do I create functions that can take my own arguments like this??

  4. Does this use the power of closures??


More From » javascript

 Answers
55

To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them.




No. They were passing a function to createServer that takes two arguments. Those functions will later be called with whatever argument the caller puts in. e.g.:



function caller(otherFunction) {
otherFunction(2);
}
caller(function(x) {
console.log(x);
});


Will print 2.



More advanced, if this isn't what you want you can use the bind method belong to all functions, which will create a new function with specified arguments already bound. e.g.:



caller(function(x) {
console.log(x);
}.bind(null, 3);
});


Will now print 3, and the argument 2 passed to the anonymous function will become an unused and unnamed argument.



Anyway, that is a dense example; please check the linked documentation for bind to understand how binding works better.


[#76385] Saturday, August 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;