简体   繁体   中英

Dynamic function call to a class's function, using settimeout


I have a class like structure in javascript, Im attempting to invoke a sibling function using a passed in function name.
This is difficulty to explain so let me show you an example of what im trying to accomplish..

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","!");

Please note that this is only a demo function, syntax errors / typos included.
Now i had this working using a dreaded Eval when it was outside the class...

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

It just required it being outside the Class and passed in dummy values for parameters

Something like this should do the trick:

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","!");

Note the custom self reference var self = this; . This is used because when the timed out function is called, the this object will be window (at least in a web browser).

Another clarification: To address a specific object property in JavaScript you can do in the following ways:

object.property; // Or
object['property']; // When you have a string literal, like in your example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM