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.
letfunction_array=["log","warn"];letfunction_to_run=1;// this would be dynamic index of arrayletcaller='console.'+function_array[function_to_run];let_1='first_parameter';let_2='Additional'+' Parameter'+'dynamically added';(newFunction(`${caller}('${_1}','${_2}')`))()
when function_to_run is 1, it will call console.warn, when it is 0, it will call console.log.
How’s it going, I'm a Adam, a Full-Stack Engineer, actively searching for work. I'm all about JavaScript. And Frontend but don't let that fool you - I've also got some serious Backend skills.
Location
City of Bath, UK 🇬🇧
Education
10 plus years* active enterprise development experience and a Fine art degree 🎨
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()}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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. linkThere is a stackoverflow page I have saved on same topic. There are few different tricks mention there, I have tried both
Function
class trick andHandler
class trick. I have not used thewindows
object trick because I feel it is exposing a lot of attack area to the windows object.Here is a working code
when function_to_run is 1, it will call console.warn, when it is 0, it will call console.log.
Ah it's so obvious now that you show me, eval type thing nice!!
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()}