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:
An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression.
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With