如何通过名称调用私有函数 [英] How invoke private function by name

查看:140
本文介绍了如何通过名称调用私有函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按名称调用函数?
实际上我知道如何按名称调用函数,但我找不到所需的范围。
所以现在我必须使用这[[ get + widgetName] ,它适用于 _get_publishedBuildsWidget1 ,但我想要make函数作为私人。

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.

所以我希望按名称调用 _get_publishedBuildsWidget2 功能

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


推荐答案

您无法通过字符串变量调用私有函数除了通过 eval(),这通常是一个坏主意。

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

}

这篇关于如何通过名称调用私有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆