简体   繁体   中英

Reuse function without global variables?

A couple of days ago I have learned on my own example how bad global variables and functions are. So apparently the best solution is NOT to use them, however sooner or later I will need to reuse my variables and functions over and over again.

So my question is: Can I reuse my functions and variables without declaring them globally? Can it be done?

For example, I want to reuse my alertBox function and my containsP variable couple of times:

DEMO: http://jsfiddle.net/ajmyZ/

//I am BAD GLOBAL FUNCTION inside var 
//But I am reusable!!! 

var alertBox = function () {
    alert("Hey I am BAD function!!")
}





$(document).ready(function () {
    //I am BAD GLOBAL var 
    //But I am reusable TOO!!! 
    var containsP = $("div p:first");
    containsP.click(function () {
        alert("Hi BAD var HERE!!");
    });

    $("p").eq(1).click(function () {
        alertBox();
    });

    //I am the NICEST function here
    //but I am NOT reusable :(

    $("p").eq(2).click(function () {
        alert("I am the NICEST function here!!");

    });

});

I guess the simplest way to avoid clobbering the global object is just to create your own "application context". You can do that, by creating a self-invoking function which wraps your whole js-code within each file.

(function( win ) {
    "use strict";

    var still_global_but_only_in_this_anonymous_closure = true;

    $(document).ready(function() {
         // ...
         // accessing the global object:
         win.some_global_property = true;
    });
}( this ));

Actually, you're already creating such a local context with your anonymous function you pass into .ready() . This is just the more explicit way. That self-invoking method, just calls itself with the global object as argument (where you still can explicitly access global variables). Furthermore, by invoking "use strict"; you're protected from accidently creating global variables alá "Ops_I_Forgot_The_Var_Statment = true;

The code you posted has no global variables. A variable declared inside of a function (in the case of your example, the anonymous document.ready handler) will never be global unless you make one of two mistakes:

  1. forget the var keyword, making an implicit global
  2. explicitly say window.myVar = ...;

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