I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.
Check out this sample code and I think you will see what I mean:
<input type="button" value="Click me" id="myButton" /> <script type="text/javascript"> var myButton = document.getElementById("myButton"); var myMessage = "it's working"; myButton.onclick = function(myMessage) { alert(myMessage); }; </script>
When clicking the button the message: it's working
should appear. However the myMessage
variable inside the anonymous function is null.
jQuery uses a lot of anonymous functions, what is the best way to pass that argument?
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.
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.
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
Your specific case can simply be corrected to be working:
<script type="text/javascript"> var myButton = document.getElementById("myButton"); var myMessage = "it's working"; myButton.onclick = function() { alert(myMessage); }; </script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/> <script type="text/javascript"> var myButton = document.getElementById("myButton"); var myMessage = "it's working"; var myDelegate = function(message) { alert(message); } myButton.onclick = function() { myDelegate(myMessage); }; </script>
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