调用变量中指定的对象的Javascript成员函数 [英] Calling a Javascript member function of an object named in a variable

查看:81
本文介绍了调用变量中指定的对象的Javascript成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下所谓的 Revealing Module Pattern ,我想使用变量调用 a 函数 b 。我怎么能这样做?

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};
}();


推荐答案

问题在于 a 不是成员,而是变量(它应该是本地变量!)。除非你使用黑暗魔法( eval ),否则你无法通过名称动态访问它们。

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};
}());

这篇关于调用变量中指定的对象的Javascript成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆