0

I have the following so-called Revealing Module Pattern and I want to call the function a inside function b using a variable. How can I do that?

foo = function() {
    a = function() {
    };

    b = function() {
        memberName = 'a';
        // Call a() using value stored in variable `memberName`.
    }

    return {b: b};
}();

2 Answers 2

2

The problem is that a is not a member, but a variable (and it should be a local one!). You cannot access those dynamically by name unless you use dark magic (eval).

You will need to make it a member of an object, so that you can access it by bracket notation:

var foo = (function() {
    var members = {
        a: function() { }
    };

    function b() {
        var memberName = 'a';
        members[memberName].call();
    }

    return {b: b};
}());
Sign up to request clarification or add additional context in comments.

Comments

1
foo = function() {
    var inner = {
      a : function() {
      }
    };

    b = function() {
        memberName = 'a';
        // Call a() using value stored in variable `memberName`.
        inner[memberName]();
    }

    return {b: b};
}();

Comments

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.