Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function dynamically in Javascript

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.

like image 350
Cxodael Avatar asked Oct 12 '14 18:10

Cxodael


People also ask

How to call a function in JavaScript dynamically?

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() { ... }

What is dynamic function in JavaScript?

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.

How do you call function in JavaScript?

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.

How do you create a dynamic function?

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);


1 Answers

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, ...);
like image 171
SLaks Avatar answered Oct 02 '22 13:10

SLaks