Calling a function by a string in JavaScript and staying in scope

≡放荡痞女 提交于 2020-01-24 01:22:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/1884637/calling-a-function-by-a-string-in-javascript-and-staying-in-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!