2

I can't seem to dynamically call the private method add from a public function. It seems that this only accesses the public scope which is why I'm not able to call add. Is there a way to do this?

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

Plus I'm not exactly sure what null is supposed to do considering you can also use this in the apply argument. Could I also have some clarification on what the first argument of apply is supposed to do? Since this is also related to my original question. Thanks in advance for any help!

4

2 回答 2

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()您的优势来检查对象

于 2013-08-14T10:54:48.187 回答
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] ) );
于 2013-08-14T10:43:52.900 回答