What is the method to call a private function using its name?

How can I call a function by its name? I understand how to call a function by name, but I am struggling to find the necessary scope. Currently, I am using this["get" + widgetName], which works for _get_publishedBuildsWidget1 but I would like to make the function private.

My goal is to call the function _get_publishedBuildsWidget2 by its name.

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

Answer №1

Accessing private functions through a string variable is not recommended, as it usually requires the use of eval() which is considered a risky practice.

Instead, a safer approach is to create a private object that holds references to these private methods, allowing easy access to them by indexing into the object:

function serviceWidgetGenerator(...) {

    var privateMethods = {
        method1: method1
        ...
    };

    privateMethods['method1']();

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

What is the reason for the error that Express-handlebars is showing, stating that the engine

I recently added express-handlebars to my project and attempted the following setup: const express = require("express"); const exphbs = require('express-handlebars'); const app = express(); app.engine('.hbs', engine({defaultL ...

Assigning controller variables within an ajax request

I'm new to AngularJS and I have a question about controller attributes. I've created an attribute called 'anuncio', which contains an array of objects as shown below: var anuncioModule = angular.module('anuncioModule',[]); a ...

Troubles arising from React component integration with Gatsby JS

As I dive into creating a stunning portfolio website with Gatsby js, I encountered an issue while trying to integrate the card component from the gatsby-plugin-material-ui package. The card resides in a separate file within my components directory and is e ...

bootstrap 4 - logo in navbar brand stays the same even when scrolling

I integrated Bootstrap 4 and successfully created a navbar. However, I am encountering a conflict when trying to change the navbar logo upon scrolling down. Despite my efforts, it is not functioning as expected. Does anyone know how to resolve this issue? ...

Troubleshooting: Issue with Vue-Router failing to load component

I have been in the process of developing a website using Vue and Vue-Router locally. Upon completion, I push my changes with git to the production server which updates the site files. Recently, I encountered an issue with a payment status page that is wor ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

What is the best way to manage individual properties in React (Next.js)?

import React from 'react'; import { makeStyles} from '@material-ui/core/styles'; import {Select, MenuItem} from '@material-ui/core'; import useState from 'react'; const sample = () => { const data = [ {TITLE : & ...

Retrieve an image from an external web service and transfer it to a different route in Express.js

I am facing an issue with passing an image object from an external web service through a node express route. The specific problem I am encountering involves retrieving an image from a URL and attempting to pass it as is, but it seems to be not functioning ...

Creating a stationary div element solely with Javascript, excluding the use of CSS, jQuery, and HTML

I've been searching all day for a solution to this issue without any success. I apologize if I overlooked any relevant posts on the topic. Currently, I am working with Qualtrics and attempting to implement a textbox with scrolling instructions that fo ...

Adaptable design tailored for smartphones

When it comes to developing mobile websites for various platforms such as iPhone 3 and 4, Android, Blackberry Torch, etc., I usually find myself needing to slice images based on the specific platform. The challenge arises from constantly having to slice im ...

JavaScript and HTML code for clipboard functionality without the need for Flash

My challenge lies in creating a grid with numerous columns and data. The user has expressed the desire for a copy to clipboard button that will allow them to easily copy the data. Can anyone suggest ways to implement Copy to Clipboard functionality withou ...

Retrieving components of an array

I am looking to extract elements from an array, then store them in a new array and compare them to another array. The challenge is that I do not want to extract the elements in a specific order. I have tried using the .slice function for extracting element ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Guide on linking AngularJS user interface with Python server via RESTful API?

Can someone please explain the process of connecting two parts? Specifically, I am using Angular CLI for the front-end and Python for the logic. My goal is to send text responses from the front-end to my Python back-end and receive a response in return. ...

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

Are there any android app frameworks similar to AngularJS?

When it comes to simplifying the rendering of repetitive elements on Android apps, is there an equivalent to AngularJS's ng-repeat directive that can make the process easier? This would prove especially helpful for creating components such as newsfeed ...