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

后端 未结 2 699
日久生厌
日久生厌 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};
    }());
    

提交回复
热议问题