我似乎无法从公共(public)函数中动态调用私有(private)方法 add
。 this
似乎只能访问公共(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/