how to assign default value for arguments when using the new Function method?
let fileName = "fileone.js", args = [], options = {};
let ls = new Function('fileName', 'args', 'options', 'somefunctionorValue', `....some...code...body...here`)
ls(fileName, args, options)
I want to assign the default value for 'someFunctionOrValue'
when the function I am creating is done: new Function(....)
.
2
Answers
I think you have to do it the usual manner, with
=
operator.This is from the docs:
Unfortunately
new Function
defines a function in a global scope without access to the local scope 🤷♂️. You should assign your default value to the global scope (not good):Some solution could be use a symbol (not elegant though):
Maybe some global object could look better:
Also remember that you can replace
Function
with a function witheval
. Buteval
will have access to the local scope which could be not preferable in some particular case in your app:Avoiding the local scope could be wrapping into
Function
🤣:But constructing
Function
every call isn’t optimal so the final solution 😁: