Passing arguments in anonymous functions in JavaScript -


sometimes see javascript written argument provided has set value or object methods. take jquery example instance:

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

when logging i, value of whatever i in iteration when looking @ selectors children in jquery each method.

take 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 request , response being passed , contain own methods can acted on.

to me, looks passing function createserver function 2 arguments have methods attached them.

my question multipart one:

  1. where these arguments come from?
  2. if these anon functions, how receive arguments can acted on other functions?
  3. how create functions can take own arguments this??
  4. does use power of closures??

to me, looks passing function createserver function 2 arguments have methods attached them.

no. passing function createserver takes 2 arguments. functions later called whatever argument caller puts in. e.g.:

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

will print 2.

more advanced, if isn't want can use bind method belong functions, create new function specified arguments bound. e.g.:

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

will print 3, , argument 2 passed anonymous function become unused , unnamed argument.

anyway, dense example; please check linked documentation bind understand how binding works better.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -