使用来自 json 对象的参数动态调用方法/函数

Call a method/function with arguments from json object dynamically

本文关键字:调用 动态 方法 函数 参数 json 对象      更新时间:2023-09-26

我有一个 JSON 对象,如下所示

var jsonData = {
    getData1:function(id1, id2){
    },
    getData2:function(id1, id2){
    }
};

我在separate variables中有一个method name(例如:getData1(和arguments(id1,id2(。

手动我可以按如下方式调用该方法

jsonData.getData1(id1, id2);

但我想通过传递 2 个参数(id1、id2(动态调用一个方法。 正确的方法是什么?

请记住,jsonData.getData1只是jsonData['getData1']的快捷方式,但在后一个版本中,您放在方括号内的内容可以是任何表达式,而不仅仅是文字。所以你可以做到:

var methodName = "getData1";
jsonData[methodName](id1, id2);
这可能是

附加到每个函数的调用方法的情况。

jsonData[methodName].call(id1, id2)

在 JavaScript 中,对象的属性也可以通过数组符号轻松访问。因此,在您的情况下:

jsonData.getData1(id1, id2);

jsonData['getData1'](id1, id2); 

以同样的方式行事。您还可以执行以下操作:

var methodName = document.getElementById('methodNameInput').value;
jsonData[methodName](id1, id2); 

methodName只需要是一个字符串。

更多:

var ob = {
   foo: 'hello',
   bar: function(x) {
     return x+'!';
   }
 };
 console.log(ob['foo'] + ' ' + ob['bar']('world'));   // prints "hello world!"
 console.log(ob.foo + ' ' + ob.bar('world'));         // prints "hello word!"