DEV Community

Adam Crockett 🌀
Adam Crockett 🌀

Posted on

Progmattic method chaining

Can I have an array/map of method names which represent an ordinarily chainable method call

[['add'],['subtract']]
Enter fullscreen mode Exit fullscreen mode

And have them build up the chain progmatticaly, can you provide some pseudo code?

Top comments (4)

Collapse
 
abhinav1217 profile image
Abhinav Kulshreshtha

Something like metaprogramming?

There is an old trick we used at old work, which uses Function.prototype.call . You can use an object of Function class itself to call dynamic functions from string. link

There is a stackoverflow page I have saved on same topic. There are few different tricks mention there, I have tried both Function class trick and Handler class trick. I have not used the windows object trick because I feel it is exposing a lot of attack area to the windows object.

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()}