简体   繁体   English

使用settimeout动态调用类的函数

[英]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. 我在javascript中有一个类似结构的类,我试图使用传入的函数名称来调用同级函数。
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进行这项工作...

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; 注意自定义自引用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). 之所以使用它,是因为调用超时功能时, this对象将是window (至少在Web浏览器中)。

Another clarification: To address a specific object property in JavaScript you can do in the following ways: 另一个说明:要解决JavaScript中的特定对象属性,可以通过以下方式进行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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