Should I use a global variable and if not, what instead? (Javascript)

后端 未结 5 797
后悔当初
后悔当初 2020-12-30 17:02

I\'m working with several functions which need to pass a variable back and forth. Should I use a global variable or another method instead? I would also appreciate an exampl

5条回答
  •  清歌不尽
    2020-12-30 17:45

    Global variables should be avoided in reusable scripts.

    If you're writing simple functions that will only be used in one page, there's nothing wrong with using globals.

    If you're writing a reusable component or a complex web page, you should use closures or namespaces instead.

    For more specific advice, please provide more detail.

    EDIT: You should create an XmlData class.

    For example:

    function XmlData(...) { 
        this.data = ...;
    }
    XmlData.prototype.doSomething = function(...) { 
        //Use this.data
    }
    

    Depending on how what your data comes from, you may want to make a separate function to retrieve the data.

    Here is a good explanation.

提交回复
热议问题