skip to Main Content

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


  1. I think you have to do it the usual manner, with = operator.

    var sum = new Function('a = 1', 'b = 2', 'return a + b');
    
    console.log(sum()); // Outputs: 3
    
    
    console.log(sum(5, 7)); // Outputs: 12
    

    This is from the docs:

    As the parameters are parsed in the same way as function expressions, whitespace and comments are accepted. For example: "x", "theValue = 42", "[a, b] /* numbers /" — or "x, theValue = 42, [a, b] / numbers */". ("x, theValue = 42", "[a, b]" is also correct, though very confusing to read.)

    Login or Signup to reply.
  2. 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):

    {
      window.def = () => 'test';
    
      const fn = new Function('fn = def', 'return fn()');
    
      console.log(fn());
    }

    Some solution could be use a symbol (not elegant though):

    {
      const id = Math.random().toString().slice(2);
      window[Symbol.for(id)] = () => 'test';
    
      const fn = new Function(`fn = window[Symbol.for('${id}')]`, 'return fn()');
    
      console.log(fn());
    }

    Maybe some global object could look better:

    {
      
      MyGlobals.def = () => 'test';
    
      const fn = new Function(`fn = MyGlobals.def`, 'return fn()');
    
      console.log(fn());
    }
    <script>
    window.MyGlobals = {};
    </script>

    Also remember that you can replace Function with a function with eval. But eval will have access to the local scope which could be not preferable in some particular case in your app:

    {
      const def = v => v;
      const x = 'test';
    
      const fn = (fn = def) => eval('fn(x)');
    
      console.log(fn());
    }

    Avoiding the local scope could be wrapping into Function 🤣:

    {
      const def = () => 'test'; 
    
      const fn = (fn = def) => (new Function('fn', 'return fn()'))(fn);
    
      console.log(fn());
    }

    But constructing Function every call isn’t optimal so the final solution 😁:

    {
      const def = () => 'test'; 
    
      const fn = (() => {
        const cached = new Function('fn', 'return fn()');
        return (fn = def) => cached(fn);
      })();
    
      console.log(fn());
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search