简体   繁体   中英

How invoke private function by name

How invoke function by name? Actually I know how invoke function by name, but I can't find needed scope. So now I have to use this[" get " + widgetName] , it is works for _get_publishedBuildsWidget1 but I want make function as private.

So I want invoke by name _get_publishedBuildsWidget2 function

    function widgetGeneratorService(commonDashboardService, $filter, buildService, $state) {

            var widgetGeneratorServiceFactory = {};

            widgetGeneratorServiceFactory._get_publishedBuildsWidget1 = function (widget) {
                widget.name = "Test",
                return widget;
            }
            var _get_publishedBuildsWidget2 = function(widget){
    widget.name = "Test",
                return widget;
    }

            widgetGeneratorServiceFactory.getDefaultWidget = function (widgetName) {
                var defaultWidget = {};
                //TODO rewrite!!!
                var fnGenerateWidget = this["_get_" + widgetName];
                if (typeof fnGenerateWidget === 'function') {
                    return fnGenerateWidget(defaultWidget);
                }


                return defaultWidget;

            }

            return widgetGeneratorServiceFactory;
        };

You can't invoke private functions via a string variable except via eval() , and that's generally a bad idea.

However you can trivially create a private object that contains references to those private methods, and then index into that to get the desired function:

function widgetGeneratorService(...) {

    var methods = {
        func1: func1
        ...
    };

    methods['func1']();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM