Use the same variable for a method and a propertie in an object

Viewed 49

after 1 hour of trying to figure out how I can get this to work I gave up and decided to ask here.

So I created an object :

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

And what I'm doing is ask for an input and show the corresponding text.

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

The problem is everything works fine with color, effect, duration, price but test return function() { return "test good" }

If I use x = document.getElementById("potions").innerHTML="Potion 1 : " + potion1[x](); test works fine but all of the others return nothing

So I was wondering if it was possible for x to work with color, effect, duration, price and test.

2 Answers

You can make test a getter.

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

the easy answer would be to turn everything into a function

or you could use the ternary operator:

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