javascript call a method with a name stored onto a variable

92 views Asked by At

I'm very new to js programming. I'm working for test development. I have requirement to call a js function with the name that is store onto a file. For example I have two files,

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

There are 2 answers

0
Barmar On BEST ANSWER

You can access an object property dynamically using bracket notation.

But in your example, you seem to have the wrong name for the method. test is the name of the constructor, the method is called logFunc. You need to call the constructor function first, it will return an object, and then you can access the method dynamically.

To provide the arguments dynamically, you have to put them into an array, not an object. Then you can use Function.prototype.apply() to call the method.

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);
0
Tim Consolazio On

You can use "bracket notation".

someObject [ someVariable ] ( theArguments ) 

If someObject (including "this") has a function named whatever the value of that variable is, it will be called with those arguments.