Luis
Luis

Reputation: 1097

Toggle function from variable

Let's say I have function x.a() and x.b(). I want to decide which function execute vía variable but it's not working my way. Here's my code and I hope you can help me.

var x = { 
    y: function(f, g){
        f(g);
    }
    a: function(txt){
        console.log(txt);
    },
    b: function(txt){
        console.error(txt);
    }
}

So when I call x.y("a", "Some text"); it does the same as if i call x.a("Some text");.

Thanks!

Upvotes: 0

Views: 106

Answers (1)

Ry-
Ry-

Reputation: 224904

Use brackets to access an object's property by name:

var x = { 
    y: function(f, g) {
        this[f](g);
    },
    a: function(txt) {
        console.log(txt);
    },
    b: function(txt) {
        console.error(txt);
    }
};

Upvotes: 2

Related Questions