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!

Tek
  • 2,592
  • 5
  • 41
  • 69
  • [.apply()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) – Andreas Aug 14 '13 at 10:45
  • @Andreas I already read that, I'm still not clear on the purpose of the first argument however. – Tek Aug 14 '13 at 10:54
  • The first argument specifies the value which is accessible via `this` in the function. `function foo() { console.log("this.bar = " + this.bar); } foo.apply({ bar: 5 }, null);` will log `this.bar = 5` – Andreas Aug 14 '13 at 11:13

2 Answers2

0

add is not a part of this. Therefore you cannot use this[testMethodFunction]. If you want to keep privacy, then you can use something like this:

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] ) );
freakish
  • 48,318
  • 8
  • 114
  • 154
0

This is because add() is not a property of Test, it is only a local variable in the Test() closure.

Here's a sample code:

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

Some tips for you:

  • Do use upper case for Class-like constructs (Test instead of test)

  • Use log() to your advantage to inspect objects

leesei
  • 5,812
  • 2
  • 24
  • 46