如何按名称调用私有函数

How invoke private function by name

本文关键字:函数 调用 何按名      更新时间:2023-09-26

如何按名称调用函数?实际上我知道如何按名称调用函数,但我找不到所需的范围。所以现在我必须使用这个["get" + widgetName],它适用于_get_publishedBuildsWidget1但我希望将函数设为私有。

所以我想按名称_get_publishedBuildsWidget2函数调用

    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;
        };

你不能通过字符串变量调用私有函数,除非通过 eval() ,这通常是一个坏主意。

但是,您可以简单地创建一个私有对象,其中包含对这些私有方法的引用,然后索引到该对象以获取所需的函数:

function widgetGeneratorService(...) {
    var methods = {
        func1: func1
        ...
    };
    methods['func1']();
}