views:

86

answers:

1

Hi, I've been playing around and searching a bit, but I can't figure this out. I have a pseudo private function within a JavaScript object that needs to get called via eval (because the name of the function is built dynamically). However, the function is hidden from the global scope by a closure and I cannot figure out how to reference it using eval().

Ex:

var myObject = function(){
    var privateFunctionNeedsToBeCalled = function() {
        alert('gets here');
    };

    return {
        publicFunction: function(firstPart, SecondPart) {
            var functionCallString = firstPart + secondPart + '()';
            eval(functionCallString);
        }
    }
}();

myObject.publicFunction('privateFunctionNeeds', 'ToBeCalled');

I know the example looks silly but I wanted to keep it simple. Any ideas?

+5  A: 

The string passed to eval() is evaluated in that eval()'s scope, so you could do

    return {
        publicFunction: function(firstPart, SecondPart) {
            var captured_privateFunctionNeedsToBeCalled = privateFunctionNeedsToBeCalled;
            var functionCallString = 'captured_' + firstPart + secondPart + '()';
            eval(functionCallString);
        }
    }

However, a better solution would be to avoid the use of eval() entirely:

var myObject = function(){
    var functions = {};
    functions['privateFunctionNeedsToBeCalled'] = function() {
        alert('gets here');
    };

    return {
        publicFunction: function(firstPart, secondPart) {
            functions[firstPart+secondPart]();
        }
    }
}();

myObject.publicFunction('privateFunctionNeeds', 'ToBeCalled');
moonshadow
Second solution looks great, thanks
rr
In your second solution, I would recommend you to use an empty object rather than an Array for the `functions` variable, eg. `var functions = {};`
CMS
@CMS: so changed.
moonshadow
Destroy the vile `eval`! No more may it darken our scripts with its putrescent presence!
bobince