Invoking a class method through a dynamic function call with the use of setTimeout


In my JavaScript code, I have a structure similar to a class where I'm trying to call a function from the same level using a passed-in function name.
Explaining this is a bit challenging, so let me illustrate with an example of what I'm aiming for.

function windowFactory(){
    this.init = function(functionName,args[]){
        SetTimeout(functionName(args),2000)
    }
    this.func1 = function(var1){
        alert(var1);
    }
    this.func2 = function(var1, var2){
        alert(var1+var2);
    }
}
var win1 = new windowFactory();
win1.init("func1","hello");
var win2 = new windowFactory();
win2.init("func2","world","!");

This snippet demonstrates a simplified scenario, including syntax errors and typos.
Previously, I managed to achieve this by using Eval outside the class...

eval(funcName+"('"+darray[1]+"','"+darray[2]+"')");

It worked by moving it outside the Class and passing in placeholder values for parameters.

Answer №1

To solve a problem like this, you can use the following code snippet:

var windowFactory = function() {
  var self = this;
  this.init = function(functionName){
      var args = Array.prototype.slice.call(arguments, 1);
      setTimeout(function() {
          self[functionName].apply(self, args);
      }, 2000);
  };
  this.func1 = function(var1){
      alert(var1);
  };
  this.func2 = function(var1, var2){
      alert(var1+var2);
  };
};
var win1 = new windowFactory();
win1.init("func1","hello");
var win2 = new windowFactory();
win2.init("func2","world","!");

It's important to note the custom self reference var self = this;. This is necessary because when the timed out function is executed, the this object will be window (especially in a web browser).

Additionally, to access a specific property of an object in JavaScript, you have multiple options such as:

object.property; // Or
object['property']; // Especially useful when dealing with string literals

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

Animate the transition effect as soon as the block is displayed

Looking to create a smooth page transition using CSS changes with the help of Javascript (jQuery). Initially, one of the pages is set to display none. page1 = $('.page1'); page2 = $('.page2'); page1.removeClass('animate').cs ...

Access data from previous request and transmit it to another request in a Node.js environment

I am facing a situation where I need to extract the parsed json response from a variable in a POST request, store it in a new variable, and then pass that variable in the headers for a subsequent GET request. However, my current approach is not yielding th ...

Eliminating blank elements from arrays using JavaScript

I'm looking for some assistance in deciphering the functionality of my code. I'm trying to create a function that will take a string as input and eliminate all letters, leaving only numbers behind. The goal is to have this function return an arra ...

The RouterView component seems to be malfunctioning within the Vue project

I recently started working on a vue-project where I created a Home page with a sideBar component and a routerView component. Here's a preview: https://i.sstatic.net/f51tdsZ6.png When clicking on any sidebar item, the router navigates to the corresp ...

Issues with syntax in AJAX programming can be a significant road

I have a function linked to an onclick button event. This function sends data via ajax to another php file. Everything was working smoothly until I tried to add an IF statement to the 'success' section, which would receive true or false from an e ...

Checking the Ajax request with an if statement

$("#Submit").click(function(event){ event.preventDefault(); var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Da ...

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

Why does AngularJS treat $http response.data as an object, even though PHP sends back a JSON string?

I am struggling with an AJAX call to PHP. The Angular code seems simple: $http( { // ... } ) .then( function cf_handle_success( response ) { console.log( response.data ) ; // --> [object Object] } , ...

What is the best way to bring a "subdependency" into ES6?

I am dealing with a situation where I have a package called react-router, which relies on another package called path-to-regexp. The challenge is that react-router does not provide its own import of path-to-regexp. So, I am wondering how I can import the e ...

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

Using p:spinner in combination with p:ajax and f:param resulted in the bean method being executed multiple times

Currently, I am working on a project using Primefaces 4.0, JSF Mojarra 2.1.7, and jBoss_7.1.1_Final. The main feature of the tool I am developing is a dialog window that displays a dataTable with dynamic columns (p:columns). These dynamic columns contain ...

Include the providers after declaring the AppModule

When it comes to Angular 2+, providers are typically registered in the following manner: // Using the @NgModule decorator and its metadata @NgModule({ declarations: [...], imports: [...], providers: [<PROVIDERS GO HERE>], bootstrap: [...] }) ...

Exploring Methods to Iterate through an Object Utilizing Two Arrays

Attempting to iterate through states passed as props in another component state = { question:[firstQ, secondQ, thirdQ], tag:[[1,2,3],[4,6],[a,b,c,d]] } I aim to display it on the next Componet with a pattern like: FirstQ [tag1] SecondQ ...

The initial page in jqgrid may show rowobject value as undefined, but subsequent pages will display the correct rowObject values

While working with jqgrid-4.8, I encountered an issue where the rowObject value is coming up as undefined in the first page but values are received in subsequent pages when using rowObject.name. However, if rowObject[0] is used, the values of rowObject are ...

Enhancing the appearance of dropdown menus for WooCommerce Variable products with custom CSS styling

I currently have a Wordpress website with WooCommerce and several variable products. Each product's variation has a dropdown menu that displays different options when clicked. My main concern is how to customize the appearance of these dropdown menus ...

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

Using NodeJS to generate a multipart/mixed response

I am faced with a particular situation: creating a multipart/mixed response in NodeJS with full control over the communication on both ends to avoid interoperability issues. A JSON file containing a list of nodes describing each ZIP file, for example: [{ ...

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...