对对象中的方法和属性使用相同的变量



经过一个小时的努力,我放弃了,决定在这里提问。

所以我创建了一个对象:

var potion1 = {
color: "red",
effect: "strength",
duration: 1+" minute",
price: 10,
test: function() {
return "test good"
}
}

我正在做的是要求输入并显示相应的文本。

var x = prompt();
x = document.getElementById("potions").innerHTML="Potion 1 : " + potion1[x];

问题是颜色、效果、持续时间和价格都很好,但测试返回function() { return "test good" }

如果我使用x = document.getElementById("potions").innerHTML="Potion 1 : " + potion1[x]();测试效果良好,但所有其他测试都不返回

所以我想知道x是否有可能处理颜色、效果、持续时间、价格和测试。

您可以使test成为getter。

var potion1 = {
color: "red",
effect: "strength",
duration: 1 + " minute",
price: 10,
get test() {
return "test good"
}
}

简单的答案是把所有东西都变成一个函数

或者你可以使用三元运算符:

x = document.getElementById("potions").innerHTML="Potion 1 : " + 
(typeof potion1[x] != 'function' ? potion1[x] : potion1[x]());

最新更新