Dynamic call function in Javascript

I want to dynamically call a function from a string like "User.find". A script will call the find () function on the User object, if that function exists. Here's what I've 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 cannot use window as it is a node.js issue, the script is not executed in the browser.

+3


source to share


4 answers


You are completely misunderstanding call()

.

call()

allows you to call a method with another this

.



You want to get as a property by name:

object[methodName](arg1, arg, ...);

      

+7


source


Method of use fn.call

and fn.apply

-

fn.call(context, arg1, arg2, arg3);

      

or



fn.apply(context, [arg1, arg2, arg3]);

      


If you can't boil your code down to any of these simple statements, calling a function dynamically is not for you.

+2


source


You can actually achieve this. First you need to get scope

where your namespace / function / object is defined.

For example, in your code, I would assume it window

.

So, a slight modification to your code will produce the desired result:

var User = {};
User.find = function(x){
    alert(x);
}

 var input = 'User.find';
 var some_data_array = {name: 'John Doe'};
 var method = input.toString().split('.');
 var nameObj = global[method[0]];
 var methodToCall = method[1];

 nameObj[methodToCall](some_data_array.name);

      

Note the use global[]

. This is where it starts.

[edited] * Modified code to use global

instead of window

as used in nodejs

.

+1


source


What you want to do is access the global object.

This should work:

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

"use strict";
var global = (1,eval)("this");
alert(global[nameObj][methodToCall](some_data_array));

      

0


source







All Articles