动态调用对象的私有函数

时间:2013-08-14 10:35:45

标签: javascript

我似乎无法从公共函数动态调用私有方法addthis似乎只访问公共范围,这就是我无法调用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] ) );

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

2 个答案:

答案 0 :(得分:0)

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] ) );

答案 1 :(得分:0)

这是因为add()不是Test的属性,它只是Test()闭包中的局部变量。

以下是示例代码:

function Test()
{
    var _priv = {
        add: function ( int1, int2 )
        {
            console.log(int1, int2);
            return int1 + int2;
        }
    };

    this.callFunc = function( testMethodFunction, methodArguments )
    {
        console.log(_priv);
        return _priv[testMethodFunction].apply(null, methodArguments);
    }
}

var t = new Test();

console.log(t);

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

一些提示:

  • 对类似类似的构造使用大写(Test而不是test

  • 使用log()来检查对象

相关问题