How can I pass arguments to anonymous functions in JavaScript?

前端 未结 10 1458
别那么骄傲
别那么骄傲 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);
    

提交回复
热议问题