0

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!

1 Answer 1

2

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);
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

Both the OP code and yours are missing a comma after the declaration of y (for the record, I'm not the downvoter).
@minitech—perhaps the downvoter would rather cop the reputation hit than edit your post to add the comma (if that was the reason).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.