DEV Community

Discussion on: Progmattic method chaining

Collapse
 
abhinav1217 profile image
Abhinav Kulshreshtha

Here is a working code

let function_array =["log","warn"];
let function_to_run = 1;  // this would be dynamic index of array
let caller = 'console.' + function_array[function_to_run];
let _1 = 'first_parameter';
let _2 = 'Additional' + ' Parameter' + 'dynamically added';
(new Function(`${caller}('${_1}','${_2}')`))()
Enter fullscreen mode Exit fullscreen mode

when function_to_run is 1, it will call console.warn, when it is 0, it will call console.log.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Ah it's so obvious now that you show me, eval type thing nice!!

Thread Thread
 
abhinav1217 profile image
Abhinav Kulshreshtha • Edited

According to MDN docs, its not exactly eval. Every function in js is an object of Function class, so this is just manual work to implement same thing.

One drawback is that this will create an object everytime for execution and mark it for garbage collection, so if you have a fix set of functions that just needs to be called dynamically, use conditional logic like `if ('add') { this.add()}