简体   繁体   中英

Why don't functions work after wrapping them in an anonymous function?

I was told to avoid public variables and conflicts, it is better to place the whole plugin in an anonymous function. I tried to do this but functions do not work anymore.

Here is a simple example:

 (function($) { function changeIt() { $("button").text("off"); } }(jQuery)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="changeIt()">On</button> 

the function runs by a HTML element but since it is inside another function, the element cannot find it.

1- How can I make it working?

2- Is it a good approach to make sure public variables are covered and assumed as private ones?

Thanks

This has to do with scope. The changeIt function only exists within the function($). If you want to add it to public scope its best to create an object the prototype the functions.

(function($) {}(jQuery)); -> This will create a private scope, basically your function won't be defined inside window , but inside this private scope.

<button onclick="changeIt()">On</button> -> This will try to execute changeIt from window , which will be undefined .

It's because the function is no more in the global object and thus the onclick event handler in the html element cannot find it by name.

Change your html to

<button id="mybutton">On</button>

and your code to

(function($) {

  $("#mybutton").click(function(){
    $("#mybutton").text("off");
  });

}(jQuery));

and it will work because the handler will not need to be looked up by name

inline events defined on elements only have access to the global scope, so, when you moved that function out of the global scope and into the scope created by the anonymous function, it was no longer accessible to the inline event.

You have two options:

Stop using inline events

(function($) {

  function changeIt() {
    $("button").text("off");
      }
      $("button").click(changeIt);

 }(jQuery));

Or define it globally

//(function($) {

  function changeIt() {
    $("button").text("off");
  }

//}(jQuery));

Since changeIt is not found in the global scope ( window in the case of a browser), the function isn't triggered on a click. In fact, your console should show an exception like: "Uncaught ReferenceError: changeIt is not defined".

To remedy this, and keep your function structure, set the handler from within the "onload" handler:

 (function($) { $('#myBtn').on('click', function () { $("button").text("off"); }); }(jQuery)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="myBtn">On</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM