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

Reposition the div element on mobile devices using media queries

Hello, I'm facing an issue on mobile with my website: dev site Today, I implemented a dropdown menu with flags to allow language switching. However, the dropdown in mobile is appearing under the hamburger nav bar. I was thinking of using media querie ...

Exploring options for accessing Google Maps API on iPhone without using UIWebView for processing JavaScript

I need to retrieve data from Google Maps using JavaScript, without using a webview. For example, I have two points (lat,lng) and I want to use the Google Maps API to calculate the driving distance between them. Essentially, I want to utilize the Google Ma ...

The View Component is experiencing issues with loading the CSS and JS files correctly when an AJAX call is made

Hey there! I'm having trouble loading a view component via ajax when the button is clicked. It seems like the css and javascript are not working properly. Check out the ajax call for the controller to load the component: $.ajax({ url: window.locat ...

Implementing Jquery to attach a click event immediately after adding a new row to the table, all

I have an issue where I am adding a new row to my table. Within this row, there is a button that should be clickable and trigger an event. I have come across various solutions, but they all involve using the following code: .on('click', 'bu ...

Encountering a CORS policy issue while attempting to retrieve data from an API

I have been attempting to retrieve data from the DHL API, however, I keep encountering issues due to CORS policy blocking the request. Even though I have configured the CORS policy on my backend server, the error persists. What could be the issue? Here ...

A guide on combining two counters in Vue to create a unified value

Is there a way to track the number of times two buttons are clicked individually as well as together? <div id="app"> <p><button v-on:click="counter1 += 1">Add One More Click</button></p> <p>&l ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

Can you please elaborate on how the CSS properties: -webkit-border-radius and border-radius are utilized?

What is the reason for having different values of 25px for -webkit-border-radius and border-radius in various positions? table.cal{ color: #064525c; border-spacing: 0; border: 3px solid black; -webkit-border-radius: **25px 25px** 0 0; ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Incorporate JSON data using jQuery's AJAX in MVC3

I need assistance with parsing the JSON data retrieved from a webservice through my controller. Currently, I am displaying the entire JSON string in a div as text. However, I only want to extract specific values such as "color" and "size". I am unsure of ...

What steps should I take to delete a class from my calendar after it has reached the maximum capacity of 20

I am trying to create a feature that automatically removes a class from the calendar if more than 20 people have booked it. On the admin side of the system, I can add classes to the database but need help implementing this check. Below is my current code ...

Convert an array into individual objects and include key-value pairs from a separate object

I am working with two arrays that have the same length: One is a simple array numbers = [4,5,6] The other is an array of objects objects = [ {type: "x", value: 7}, {type: "y", value: 8}, {type: "z", value: 9} ] My goal is to combine th ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

Tips for creating a JSON cross-domain call in PHP

Hello, I'm just starting to dive into JSON cross domain. I've encountered an issue that I need help with. I am trying to make a cross-domain call to PHP using JSON, but I keep encountering errors. Here is a snippet of the code that I'm worki ...

How can you toggle the visibility of a text based on the selection of a jQuery radio button?

Is it possible to dynamically enable or disable a field based on the selection of a radio button? Here are the rules: The field should only be active when the "Inactive" radio button is selected Check out the code snippet below for reference: Radio B ...

Having issues with showing an image from a specified component in a separate file

I am facing an issue where my image is not displaying in the app.js file, even though I have imported it from another file named comp.js. Here is the current code in app.js: import React from 'react'; import TextImg from "./Comp"; impor ...

Generating a JavaScript object from a string to optimize its compatibility with datatables

This inquiry pertains to the plugin available at: var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}'; var hidecolsobj = eval('(' + hidecols + ')'); ...

When trying to access $model.show() in Vue.js, the returned model is showing as undefined

I'm running into a console error message every time I try to click the button for $model.show('demo-login'): TypeError: Cannot read property 'show' of undefined Error output when the button is clicked: TypeError: Cannot read prop ...

JavaScript substring() function in clone is experiencing an error

I am currently working on a JavaScript function that determines whether a specific substring is present in a larger main string. For instance, if the main string is "111010" and the substring is "011," the expected result should be false since the substr ...

Is it possible to authenticate a user in Firebase using Node.js without utilizing the client side?

Can I access Firebase client functions like signInWithEmailAndPassword in the Firebase SDK on the server side? Although SDKs are typically used for servers and clients use JavaScript, I need a non-JavaScript solution on the client side. I have set up the ...