I've been attempting to dynamically call functions in JS. In my current situation, I'm using eval to build and call the correct function name based upon its parents arguments. Here's an example:
In a Comments "class":
$scope.getComments = function(id) {
return getApiData(id, "comments");
};
getApiData = function(id, field) {
eval("BackendApi.get" + (field.capitalize()) + "(" + id + ")");
// do something else with `field` down here
};
BackendApi is a simple REST service. The reason I'm trying to dynamically call these functions is because I found myself writing a lot of repetitive code. I've read eval is generally considered bad practice and it can be associated with poor performance. In the above example, I would attempt to call a function with this syntax:
BackendApi.getComments(:id);
Note that the Comments#$scope.getComments and BackendApi#getComments share the same function name for their respective "classes". The biggest problem I'm running into is the "get" + field part. Is it possible to call the name of the caller function of getApiData instead of "get" plus the static field name as an argument? I would appreciate help, and I apologize if I misrepresented any part of JS.
BackendApi['get' + (field.capitalize())](id)