如何通过名称调用私有函数

如何通过名称调用私有函数

问题描述:

如何通过名称调用函数? 其实我知道如何通过名称调用函数,但我找不到所需的范围。 所以现在我必须使用这个[“得到” + 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'](); 

}