javascript - 动态调用对象的私有(private)函数

标签 javascript

我似乎无法从公共(public)函数中动态调用私有(private)方法 addthis 似乎只能访问公共(public)范围,这就是我无法调用 add 的原因。有办法做到这一点吗?

function test()
{
    var actionCollection = [];

    function add( int1, int2 )
    {
        return int1 + int2;
    }

    this.callFunc = function( testMethodFunction, methodArguments )
    {
        this[testMethodFunction].apply(null, methodArguments);//Method 'add' not found.
    }
}

var t = new test();

alert( t.callFunc( 'add', [1,2] ) );

另外,考虑到您也可以在 apply 参数中使用 this,我不确定 null 应该做什么。我还可以澄清一下 apply 的第一个参数应该做什么吗?因为这也与我原来的问题有关。在此先感谢您的帮助!

最佳答案

add 不是this 的一部分。因此,您不能使用 this[testMethodFunction]。如果你想保护隐私,那么你可以使用这样的东西:

function test() {
    var actionCollection = [];

    var private_methods = {
        add: function( int1, int2 ) {
            return int1 + int2;
        }
    }

    this.callFunc = function( testMethodFunction, methodArguments )
    {
        // note the change here!
        return private_methods[testMethodFunction].apply(null, methodArguments);
    }
}

var t = new test();

alert( t.callFunc( 'add', [1,2] ) );

关于javascript - 动态调用对象的私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229432/

相关文章:

javascript - 下载带有 http header 的文件

javascript - 使文本字段根据窗口宽度适当调整大小

javascript - 如何过滤 JS 对象并按日期排序?

asp.net - PostBackUrl 在 Html 按钮上不可用

javascript - Python 的 "u"Unicode 前缀是否有等效的 Javascript?

javascript - 使用 React Router 5 时遇到问题

javascript - Firebase Cloud 在从之前的工作函数复制的代码中出现意外的 token ?

javascript - 有人可以向我解释 javascript getCookie() 中 while 循环的功能吗?

javascript - 如何使我的图像响应?

javascript - 删除功能不起作用,请帮忙