简体   繁体   中英

How to avoid global variables in WordPress

I've had a few instances now in which I create, say, a variable with css called

.slider

and it affected alot of stuff on my page. How do I avoid this?

Also, I've written alot of JavaScript in a plugin, and ended up doing changes to global variables.

Is there a way to avoid this? All of the sudden all the images might change on a page, or something in the javascript code changes stuff on the page.

It seems that your code looks like this:

var my_global_var = 123;

function do_something_with_vars() {
   //   ... your logic here

}

function do_something_else_with_vars() {
   //   ... your logic here
}

One way to avoid global variables conflict is to use anonymous functions:

The above code can be re-written as:

(function(){
   var my_global_var = 123;
   function do_something_with_vars() { ... };
   function do_something_else() {  ... };
})();
// here, my_global_var is out of scope.

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