0

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.

2
  • 1
    This is why Angular is great, it brings out the best in the developer. Commented Jun 11, 2014 at 15:47
  • 2
    BackendApi['get' + (field.capitalize())](id) Commented Jun 11, 2014 at 15:49

1 Answer 1

1

You can use array notation to access properties by name:

getApiData = function(id, field) {
    return BackendApi['get' + field.capitalize()](id);
}
Sign up to request clarification or add additional context in comments.

4 Comments

This worked, thank you! As a side question, is it possible in JS to get the name of the caller function without passing it through as a parameter to the child function?
the caller function might not have a name, it could be an anonymous function.
Maybe you should really be using OO programming, so you can use this.
Yeah, I tried that, but it just feels weird with Angular (this.$scope.getComments).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.