开发者

What is the best way to store a value for use in a later function? I'm hearing global variables are evil

So the code I'm using is at http://jsfiddle.net/8j947/10/ and it returns a value of true or false for the variable isLive. How can I use the variable onLive in a later function? I read the answers at Accessing variables from other functions withou开发者_开发百科t using global variables, but I'm having a lot of trouble getting it to work. All I want is to store the value, true or false, so I can call it into an if statement in a later function. Can anyone give me the simplest way to do this? Is there a way to store the data as an object?


Just define your variable in the same scope as you are defining your functions that rely on it. If your functions are in the global scope, then so should your variable be.

If you are developing a plugin or control or a script that will be used in more than one page, then yes, avoid global variables. If, on the other hand, you have a page-specific piece of data that you need available in more than one location, a global variable is absolutely appropriate.

Sometimes you have to understand the rules, so that you know when it's ok to break them.

Now, if you just now realized that your functions are in the global scope, and you want to change that, just wrap all of your code in an anonymous function and call it immediately:

(function(){
    var scopeLevelVariable = true;
    function scopeLevelFn(){
        ...
    }
    window.globallyAvailableVariable = "foo";
    window.globallyAvailableFunction = function(){
        ...
    };
})();


Global variables are considered "evil", because any function could inadvertently modify your variable, which can cause some hard-to-track bugs. This usually isn't a problem for simple projects, but it's something you should think about.

To save a value without muddying the global namespace too much, and thus reduce the risk of the aforementioned bugs, you can create you own "namespace" object (Option 2 of the accepted answer in the question you linked). Like so:

var MyPageData = {};

MyPageData.someProperty = someFunc();

// Later on...

function anotherFunc() {
    // Use the data you set...
    alert(MyPageData.someProperty);
}


I would not agree that global variables are evil in themselves, just that there are a few precautions to take whilst using them.

To avoid colision with other global variables (possibly ones written in included libraries) I would suggest taking two measures

1) Use anonymous functions (self envoking) to keep your code (and variables) seperated from other code

// other peoples/modules code
var myVariable = "whatever";

// anonymous function for your self contained code
(function(){
var myVariable = "inside closure";
alert(myVariable);
})() // the empty brackets envoke the anonymous function

// still retains value from before your self envoking anonymous function
alert(myVariable);

2) Use unique namespace - and make all globals you use under that one object to avoid polution

myUniqueNameSpaceRaiders = {};
// will not conflict with other global variables if your namespace is unique
myUniqueNameSpaceRaiders.desiredVariable = "something";

I think if you organise your global variables well, it is fine to use them. Hope this helps.


If you're working with some specific set of functions and data, you could do something like this:

var yahooInterface = new function(){
   var isLive = false;

   this.function1(){ isLive = true };
   this.function2(){ alert( isLive ) };
};

In this manner, function1 and function2 share data, but they don't wastefully pollute the global namespace.

Example: http://jsfiddle.net/XpJFn/1/


Try modular javascript programming .

Also, closures are useful for holding information w/o exposing it to the global namespace.

If you must use a global... create your own global namespace and put anything you need inside of it. This may be a good starting point for you as you venture into other javascript patterns.

Ex.

//Global Namespace
window.ns = {};

ns.onLive = false;

if(ns.onLive === false) {
   ns.notLive = !ns.onLive;
}

//Closures
var hello = (function() {

  var onLive = true;

  my.fn1 = function () {
    return onLive;
  }

  my.fn2 = function () {
    return !onLive;
  }

  return my;
})();

hello.fn1(); //true;
hello.fn2(); //false


you should have a look to localStorage : http://diveintohtml5.ep.io/storage.html


If you're deadset against using global variables, you could just create a method that returns the variable.

getVariable = function(){
    return "Hello world!";
}

Global variables are not inherently evil though, when they're used properly. Just don't use them if you don't need to. If there's a good justification for using a global variable, there's nothing wrong with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜