简体   繁体   English

是否可以从javascript中的函数内部定义全局常量变量?

[英]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"但我想从代码中的任何地方访问变量 s,因为我没有输入“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:如果你希望它是一个常量,你可以使用 defineProperty 和一个 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM