Turn a JavaScript local variable into a global variable

后端 未结 2 1533
感情败类
感情败类 2020-12-08 16:58

I have a JavaScript function to generate a variable. That function is activated by an onclick button event.

After that variable is generated, I need to use it as a gl

2条回答
  •  生来不讨喜
    2020-12-08 17:37

    Declare the variable outside the scope of the function:

    var foo = null;
    
    function myClickEvent() {
        foo = someStuffThatGetsValue;
    }
    

    Better yet, use a single global variable as the namespace ("MyApp") for your application, and store the value inside that:

    var MyApp = {
        foo: null
    };
    
    function myClickEvent() {
        MyApp.foo = someStuffThatGetsValue;
    }
    

    The function itself could even be included in there.

提交回复
热议问题