![](/img/trans.png)
[英]Is it possible to define a global constant from within a function in javascript
[英]is it possible to define a global constant variable from inside a function in javascript?
我想做这样的事情:
function defineGlobalConst(){
const s = 10;
}
但我想从代码中的任何地方访问变量 s,因为我没有输入“const”
您可以像这样定义一个全局变量:
在浏览器中:
function defineGlobalConst(){
window.s = 10;
}
在节点:
function defineGlobalConst(){
global.s = 10;
}
如果你希望它是一个常量,你可以使用 defineProperty 和一个 getter:
Object.defineProperty(window, "s", {
get: () => 10,
set: () => { throw TypeError('Assignment to constant variable.') },
});
您唯一的选择是将值存储在窗口中。 请务必至少命名您的值,因为它可能与窗口中已有的其他内容冲突:
// Create the namespace at the beginning of your program.
if (!window.MY_APP) {
window.MY_APP = {};
}
window.MY_APP.s = 10;
可以通过使用反模式来解决您的问题。 请注意,我不提倡这种方法,但从纯粹的“你能做到吗”的角度来看,在函数中分配的任何未声明的变量在默认情况下都会变成一个全局变量(当然这不会像你一样创建一个常量已经问过了,但我想我还是会展示它):
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.