I want to dynamically call a function from a string like "User.find". A script would call the function find() in the object User if the function exists. Here's what I tried:
 var User = {};
 User.find = function(){
     return 1;
 }
 var input = 'User.find';
 var some_data_array = {name: 'John Doe'};
 var method = input.toString().split('.');
 var nameObj = method[0].substring(0,1).toUpperCase() + method[0].substring(1);
 var methodToCall = method[1];
 nameObj.call(methodToCall, some_data_array);
But it always returns:
 nameObj.call(methodToCall, some_data_array);
 TypeError: Object User has no method 'call'
Any idea? I can't use window since it is a node.js problem, the script is not executed in the browser.
function MyClass() { this. abc = function() { alert("abc"); } } var myObject = new MyClass(); myObject["abc"](); If what you want to do is not only dynamically call a function but also dynamically create a named function, it is also best done with the window object using either: window['name'] = function() { ... }
The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
Creating The Dynamic Function The Function object can also be used as a constructor function to create a new function on the fly. The syntax for creating a function from Function Object is as follows: const myFunction = new Function(arg1, arg2, … argN, body);
You're completely misunderstanding call().
call() lets you call a method with a different this.
You want to get as property by name:
object[methodName](arg1, arg, ...);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With