How can I pass arguments to anonymous functions in JavaScript?

前端 未结 10 1413
别那么骄傲
别那么骄傲 2020-12-08 01:37

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:



        
相关标签:
10条回答
  • 2020-12-08 02:16

    The following is a method for using closures to address the issue to which you refer. It also takes into account the fact that may which to change the message over time without affecting the binding. And it uses jQuery to be succinct.

    var msg = (function(message){
      var _message = message;
      return {
        say:function(){alert(_message)},
        change:function(message){_message = message}
      };
    })("My Message");
    $("#myButton").click(msg.say);
    
    0 讨论(0)
  • 2020-12-08 02:17

    What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).

    0 讨论(0)
  • 2020-12-08 02:23

    By removing the parameter from the anonymous function will be available in the body.

        myButton.onclick = function() { alert(myMessage); };
    

    For more info search for 'javascript closures'

    0 讨论(0)
  • 2020-12-08 02:23
    <input type="button" value="Click me" id="myButton" />
    
    <script type="text/javascript">
        var myButton = document.getElementById("myButton");
    
        myButton.myMessage = "it's working";
    
        myButton.onclick = function() { alert(this.myMessage); };
    
    
    </script>
    

    This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data with the object that's calling it ( in this case myButton ).

    0 讨论(0)
提交回复
热议问题