首页 > 解决方案 > 对对象中的方法和属性使用相同的变量

问题描述

经过 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 是否可以使用颜色、效果、持续时间、价格和测试。

标签: javascriptobject

解决方案


你可以做test一个吸气剂

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

推荐阅读