3 回答

TA貢獻1827條經驗 獲得超4個贊
您可以像這樣定義一個全局變量:
在瀏覽器中:
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.') },
});

TA貢獻1725條經驗 獲得超8個贊
您唯一的選擇是將值存儲在窗口中。請確保至少為您的值命名空間,因為它可能與窗口中已有的其他內容沖突:
// Create the namespace at the beginning of your program.
if (!window.MY_APP) {
window.MY_APP = {};
}
window.MY_APP.s = 10;

TA貢獻1834條經驗 獲得超8個贊
使用反模式可以解決您的問題。請注意,我不提倡這種方法,但從純粹的“你能做到嗎”的角度來看,在函數中分配的任何未聲明的變量默認情況下都會成為全局變量(當然這不會像你一樣創建常量問過,但我想我還是會展示它):
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"
添加回答
舉報