Calling a Javascript member function of an object named in a variable

后端 未结 2 675
日久生厌
日久生厌 2021-01-28 10:19

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

相关标签:
2条回答
  • 2021-01-28 10:42

    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};
    }());
    
    0 讨论(0)
  • 2021-01-28 10:48
    foo = function() {
        var inner = {
          a : function() {
          }
        };
    
        b = function() {
            memberName = 'a';
            // Call a() using value stored in variable `memberName`.
            inner[memberName]();
        }
    
        return {b: b};
    }();
    
    0 讨论(0)
提交回复
热议问题