简体   繁体   中英

is it possible to define a global constant variable from inside a function in javascript?

I want to do something like this:

function defineGlobalConst(){
     const s = 10;
}

but I would like to access variable s from anywhere in my code, as I didn't type "const"

You can define a global variable like this:

In a browser:

function defineGlobalConst(){
     window.s = 10;
}

In node:

function defineGlobalConst(){
     global.s = 10;
}

If you want it to be a constant you could use defineProperty and a getter:

Object.defineProperty(window, "s", { 
  get: () => 10,
  set: () => { throw TypeError('Assignment to constant variable.') },
});

Your only option is to store the value in the window. Just be sure to at least namespace your value, as it could conflict with something else already in the window:

// Create the namespace at the beginning of your program.
if (!window.MY_APP) {
  window.MY_APP = {};
}

window.MY_APP.s = 10;

It is possible to solve your problem by utilizing an anti-pattern. Be advised that I'm not advocating this approach, but from a pure "can you do it" perspective, any non-declared variable that is assigned in a function becomes a Global by default (of course this does not create a constant as you've asked, but thought I would show it anyway):

 function foo(){ bar = "baz"; // implicit Global; } foo(); // Show that "bar" was, in fact added to "window" console.log(window.bar); // "baz" console.log(bar); // "baz"

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