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.
source to share
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
.
source to share
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));
source to share