javascript调用一个名称存储在变量上的方法

时间:2016-12-30 21:56:42

标签: javascript method-call

我对js编程很新。我正在为测试开发工作。我要求使用存储在文件中的名称调用js函数。例如,我有两个文件,

file1.sah

//sah is sahi extension but internally the file has javascript code only
function test(){
  this.var1 = 100;
  this.logFunc = function(a,b,c){

    console.log(a + b + c + this.var1);
  }
}

file2.sah

include file1.js //file1.js module is referenced
var obj = new test();
var $method = "logFunc";
var $params = {"a" : 1, "b" : 2, "c" : 3};

//wanted to call the method "test" from file1 and pass all arguments as like key & value pair in object
//I cannot use window objects here
eval($method).apply(obj, $params);
//eval works but I couldn't pass the object params I have. For simplicity I //have initialised params in this file. In my real case it will come from a
//different file and I will not know the keys information in the object 

2 个答案:

答案 0 :(得分:0)

您可以使用括号表示法动态访问对象属性。

但是在您的示例中,您似乎找到了该方法的错误名称。 test是构造函数的名称,该方法称为logFunc。您需要先调用构造函数,它将返回一个对象,然后您可以动态访问该方法。

要动态提供参数,必须将它们放入数组中,而不是对象中。然后,您可以使用Function.prototype.apply()来调用该方法。

var obj = new test();
var method = 'logFunc';
var params = {"a" : 1, "b" : 2, "c" : 3};
var param_array = [params.a, params.b, params.c];

obj[method].apply(obj, param_array);

答案 1 :(得分:-1)

您可以使用"括号符号"。

someObject [ someVariable ] ( theArguments ) 

如果someObject(包括" this")有一个名为该变量值的函数,则将使用这些参数调用它。

相关问题