Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  35] [ 2]  / answers: 1 / hits: 16788  / 10 Years ago, sun, october 12, 2014, 12:00:00

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.


More From » node.js

 Answers
17

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

[#69153] Thursday, October 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
farrahsavannahl

Total Points: 418
Total Questions: 108
Total Answers: 90

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
;