在JavaScript中以字符串形式传递对象名称时,我可以访问对象吗?
假设我正在这样做:在JavaScript中以字符串形式传递对象名称时,我可以访问对象吗?,javascript,object,properties,Javascript,Object,Properties,假设我正在这样做: Foo = function () {}; o = Object.create(Foo, { p: { value: 42, writable: true, enumerable: true, configurable: true } }); o.prototype.bar = function () {console.log("hello");}; var x = "o"; window.o = o; Object.defineProperty(wind
Foo = function () {};
o = Object.create(Foo, { p: {
value: 42,
writable: true,
enumerable: true,
configurable: true }
});
o.prototype.bar = function () {console.log("hello");};
var x = "o";
window.o = o;
Object.defineProperty(window[x], "foo", { value: 123});
问题:有没有办法在
o
上设置属性而不首先将其添加到另一个对象(在本例中为窗口)?是的,另一种方法是eval
。然而,将对象作为属性添加到像您这样的对象中确实是一种方法,明确限制(“白名单”)可能的名称。当然,你也可以使用if else
或switch
,但写起来很枯燥。好主意与坏主意评估
或坏主意…取决于你使用它的目的。在我的情况下,坏主意。。。我还是没想过。