Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one.

The function I need to call is popup()

random() = 'popup()'

if ($.cookie('optin-page')) {

} 

I attempted:

if ($.cookie('optin-page')) {
    window[random()];
}

Answer №1

It is not allowed to set a value to the result of calling a function. The left side of an equation using = cannot include parentheses (). (In other words, the initial line of your code contains an error).

If you wish to invoke a global function matching the output of a function named random, you can do so like this:

window[random()]();

However, in situations like these, it is advisable to store those functions in an object and then call them as its methods:

var bar = { 
    x: function () { 
        alert('For example'); 
    } 
};
function selector() { 
    return "x";
}
bar[selector()]();

Answer №2

Instead of simply calling whatever string you receive, it might be more beneficial to use a switch statement or something similar.

var functionToCall = random();

switch(functionToCall)
{
case 'popup()':
    popup();
    break;
case 'function2()':
    function2();
    break;
default:
    // throw an error INVALID FUNCTION CALLED
}

By doing this, you can implement error handling in your code.

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

Guide on populating a Kendo grid using a specific property from the server's JSON response, rather than the entire object

Here is the setup for my custom kendo grid: $("#grid").kendoGrid({ dataSource: { transport: { url: "customers", type: "GET", ...

What is the best way to evaluate user input against a string retrieved from process.stdin.on()?

I'm having trouble comparing a string with user input from process.stdin.on as it always returns false. //Let's say the user inputs 'hello' every time. process.stdin.on('data', userInput => { let text = userInput.toStrin ...

Implementing a vertical divider line in between columns with Foundation CSS

Here is the HTML code snippet: <link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet"/> <div class="card"> <div class="card-section"> <section class="row"&g ...

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

The alias for the last item in a nested ng-repeat loop will consistently evaluate to true

Within my code, I am utilizing two nested ng-repeat functions and I am looking to change the $last variable to something different for each level - let's say outerLast and innerLast. I attempted to achieve this by using ng-init="outerLast= $last" and ...

Having trouble with one of the 3 auto-refreshing divs on a page using JQuery?

I've set up three divs on my website, and each one is automatically refreshed using JQuery. Here's the HTML code: <div id="photo"> <?php require("image.php"); ?> </div> <div id="right-bar"> <div id="facebook"& ...

Running the command "npm start" in ghost (node.js) is causing an error

After successfully installing node.js, I attempted to set up Ghost. However, when running the installation for Ghost using npm install --productions I encountered the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

CSS bundling may cause rendering issues, but it functions properly when written directly on the page

When I attempt to link the CSS file within the head or put it in a bundle, it won't render properly. However, if I use inline styles, everything works fine. The application is running locally with debug set to true on Web.config - <compilation debu ...

Is there an easy way to determine if an element inside a Vue component is overflowing?

I created a unique component called ResultPill which includes a tooltip feature (implemented using vuikit). The text displayed in the tooltip is determined by a getter function called tooltip, utilizing vue-property-decorator. Here are the relevant parts o ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

CSS files are failing to load in ASP .NET framework

I am facing a similar issue to the one described by another user on Stack Overflow here: Asp.NET not applying my CSS files However, after adding the following code to my web.config file, nothing seems to change: <location path="css"> &l ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

The outer border of the Angular Material Mat Grid List is beautifully highlighted

In my project, I have a mat grid list where users can define the number of rows and columns. My goal is to display borders around each mat-grid-title cell. However, I am struggling to properly display the outermost black border for the entire mat-grid-lis ...

Struggling to locate tab link elements with Selenium using different approaches

I am encountering difficulties with Selenium in locating a specific set of tab link elements by their IDs or link text. During my usage of Selenium, I am attempting to click through each of the tabs ("DESCRIPTION AND PRICE", "FINISH", and "NOTES") and extr ...

I am attempting to adjust the CSS code so that it does not shrink when clicked on. How can I prevent this from happening?

Here is the element I am attempting to modify. I attempted &:active { flex:7;} but upon releasing the left click button, it reverted back to its original size. I was aiming for something similar to this <h1>Gallery</h1> < ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

Setting a custom tab as the default route in Expo Router without relying on an index.tsx file - here's how!

In the development of my React Native app using Expo Router, I am structuring it into main sections with a tabs layout consisting of Events, Search, and Profile. Here is an image showcasing the desired folder structure: The main sections Events, Search, ...

Combining two Angular expressions

I have two values to work with: {{columns.field}} and {{resultado.!!!}}. The challenge is that I need to include the value of {{columns.field}} inside the !!!, but I'm struggling to figure out how. I have to structure it this way because I am unsure o ...

Can a cross-browser extension be developed that integrates with a Python backend for a web application?

Present State I am currently in the initial stages of planning a web application that users will access through a browser extension designed as a horizontal navigation bar. My initial plan was to utilize Pylons and Python for this project, but I am uncert ...