我想用 global object 得到一个常量变量动态使用它,但 global.myconstant
不起作用,但 global.myvar
起作用。
λ node
> const myconstant = true
undefined
> global.myconstant
undefined
> var myvar = true
undefined
> global.myvar
true
> global.const
undefined
我想做的:
const myconstant = () => { console.log("ok const"); };
var myvariable = () => { console.log("ok var"); };
const watchlist = {
myconstant: "file1.html",
myvariable: "file2.html"
};
Object.keys(watchlist).forEach((taskName) => {
try {
global[taskName](); //doesn't work with const
} catch (e) {
console.error("error", taskName);
}
});
实际输出:
error myconstant
ok var
想要的输出:
ok const
ok var
现场演示:https://repl.it/repls/SunnyScholarlyPasswords
如何使用字符串获取常量变量? 没有用 var
替换 const
。
最佳答案
只有用 var
声明的变量才会隐式分配给全局对象。如果要创建不可重新分配的属性,则应改用 Object.defineProperty
。例如,在浏览器中,引用 window
而不是 global
:
Object.defineProperty(
window,
'myconstant',
{
value: () => { console.log("ok const"); },
configurable: false
}
);
var myvariable = () => { console.log("ok var"); };
const watchlist = {
myconstant: "file1.html",
myvariable: "file2.html"
};
Object.keys(watchlist).forEach((taskName) => {
try {
window[taskName]();
} catch (e) {
console.error("error", taskName);
}
});
// Won't reassign, and will throw an error in strict mode:
window.myconstant = 'foo';
console.log(typeof window.myconstant);
configurable: false
是关键,虽然它是可选的 - 它默认为 false
。无法修改或删除不可配置的属性。
关于javascript - 如何在 Nodejs 中使用全局对象获取常量变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051621/