简体   繁体   中英

How to set global variables and global functions in JavaScript

In my language.js ,I have:

function setCookie(cookie) {
  var Days = 30; //this cookie will keep 30 days 
  var exp = new Date(); //new Date("December 31, 9998");
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie = cookie + ";expires=" + exp.toGMTString();
}

function setLanguage(lang) {
  setCookie("lang=" + lang + "; path=/;");
  translate(lang);
}

later on:

switch (getCookieVal("lang")) {
  case "en":
    setLanguage("en");
    break
  case "zh":
    setLanguage("zh");
    break
  default:
    setLanguage(systemLang);
}

this makes console.log(getCookieVal("lang")); print out zh . In a word, it works, however, if I use console.log(getCookieVal("lang")) in another file named data.js it doesn't work.

I really need to use getCookieVal("lang") to determine which variable to be used according to the cookie language.

Here is the full code:

var dict = {};
var systemLang = navigator.language.toLowerCase().slice(0, 2);

I already take the function out of wrapper, so now should be global function, but it is still not defined. To make question simple. You see, I make systemLang as global variable, however I use console.log(systemLang) in other .js file. It is not defined.

It sounds like these functions are in some kind of wrapper, like a jQuery ready callback:

$(function() {
    function setCookie(cookie) {
        // ...
    }
    function setLanguage(lang) {
        // ...
    }
});

or a scoping IIFE:

(function() {
    function setCookie(cookie) {
        // ...
    }
    function setLanguage(lang) {
        // ...
    }
})();

That means they're not global. If you want them to be global, be sure they're declared at the top level, not inside anything:

function setCookie(cookie) {
    // ...
}
function setLanguage(lang) {
    // ...
}

JavaScript doesn't pay any attention to what file the function is in (unless you use modules, but I don't think you are), all globals are truly global, regardless of the file.


I should note that using globals isn't generally best practice. The global namespace on browsers is very crowded. Instead, look at the various module bundlers and such.

In one file localStorage.setItem('TheVariableNameYouWant',TheValueofTheVariableYouWant);

In another file localStorage.getItem('TheVariableNameYouWant')

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