Home > Enterprise >  How can I call a function based on a string name
How can I call a function based on a string name

Time:08-22

I have a function that assigns column definition to my grid. There is one key called valueGetter which i need to assign the function to call to get the value for this column. The problem i am facing is that my API returns this value as a string.

When I set it via

valueGetter: column.valueGetter,

it looks like this valueGetter: "this.getSellerAgentandOffice" and it does not work. But if i manually set it to valueGetter: this.getSellerAgentandOffice it works. So the question is how can I set the column.valueGetter String value as a function name ?

Also just as some additional info when i tried to use

valueGetter: this[column.valueGetter],

i am getting following error

myValueGetter

To make it more clear about the issue i included a StackBlitz Sample

CodePudding user response:

To invoke a function on an object, simply reference it the same way you would if it were a property, and then invoke it with parentheses.

this.myFunction(param1, param2);

becomes

this["myFunction"](param1, param2);

Note that you CANNOT do this with simple named functions, unless they happen to be global.

window["myFunction"](param1, param2);

that is a function like myFunction below is not reachable except directly.

(function() {
  // cannot be reached by string
  function myFunction(a, b) { ... }
})();

CodePudding user response:

Not sure why the question was down voted 3 times even so i provided code and working sample. But what would one expect from some of these guys.

In any case if someone should run into a similar issue below is the code that fix the issue as i guess the error was due to fact that it could be possibly undefined or nothing.

 const valueGetter =   column.valueGetter as string;
 valueGetterFunction = this[valueGetter] || '';
  • Related