对对象中的方法和属性使用相同的变量
在试图弄清楚如何让它工作 1 小时后,我放弃了并决定在这里问。
所以我创建了一个对象:
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一个吸气剂。
var potion1 = {
color: "red",
effect: "strength",
duration: 1 + " minute",
price: 10,
get test() {
return "test good"
}
}