Javascript 对对象中的方法和属性使用相同的变量
经过一个小时的努力,我终于放弃了,决定在这里提问 所以我创建了一个对象:Javascript 对对象中的方法和属性使用相同的变量,javascript,object,Javascript,Object,经过一个小时的努力,我终于放弃了,决定在这里提问 所以我创建了一个对象: var potion1 = { color: "red", effect: "strength", duration: 1+" minute", price: 10, test: function() { return "test good"
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(“药剂”).innerHTML=“药剂1:”+potion1[x]()代码>测试工作正常,但所有其他测试均不返回任何结果
所以我想知道x是否可以处理颜色、效果、持续时间、价格和测试。简单的答案是将所有东西都转换成函数
或者可以使用三元运算符:
x = document.getElementById("potions").innerHTML="Potion 1 : " +
(typeof potion1[x] != 'function' ? potion1[x] : potion1[x]());
您可以进行test
a
简单的答案是将所有内容都转换为函数。您是否尝试对innerHTML进行条件赋值,例如使用innerHTML=“药剂1:”+typeof药剂1[x]=“函数”?药剂1[x]():药剂1[x]
?这就是所谓的条件(三元)运算符。您可以在以下网址查看更多信息:
var potion1 = {
color: "red",
effect: "strength",
duration: 1 + " minute",
price: 10,
get test() {
return "test good"
}
}