title: Is there a way to evaluate variables inside a function which are not function arguments when calling toString method?
body: <p>I'm generating PDF files in nodejs using <a href="http://pdfmake.org/playground.html" rel="nofollow noreferrer">pdfmake</a>. I'm generating tables, so for some columns I need to send formatting function.</p>
  
  <p>For example, if rows have property <code>employee</code>, whose value can be something like:</p>
  
  <p><code>{id: 1, firstName: 'John', lastName: 'Johnson'}</code>,</p>
  
  <p>For displaying this column I use following formatting function:</p>
  
  <p><code>employee =&gt; `${employee.firstName} ${employee.lastName}`</code></p>
  
  <p>So to my nodejs backend, I'm sending this function as string. Calling <code>toString</code> on this function returns the same text from above with quotes:</p>
  
  <p><code>"employee =&gt; `${employee.firstName} ${employee.lastName}`"</code></p>
  
  <p>Then I execute this function with arguments I get from database. I do this by calling <code>eval</code></p>
  
  <p><code>eval(`(${fnString})({id: 1, firstName: 'Test', lastName: 'Test'})`)</code></p>
  
  <p>And this works fine when only variables inside a function are it's arguments.</p>
  
  <hr>
  
  <p>So this is my question:</p>
  
  <p>Say I have code like this:</p>
  
  <pre><code>const prefix = 'X'
  const fn = employee =&gt; `${prefix} ${employee.firstName} ${employee.lastName}`
  </code></pre>
  
  <p><code>fn.toString()</code> evaluates to:</p>
  
  <p><code>"employee =&gt; `${prefix} ${employee.firstName} ${employee.lastName}`"</code></p>
  
  <p>But I need it to be like this:</p>
  
  <p><code>"employee =&gt; `X ${employee.firstName} ${employee.lastName}`"</code></p>
  
  <p>because I won't have access to <code>prefix</code> variable, I only send function as string to the nodejs.</p>
  
  <p>Is there a way to evaluate variables inside a function when calling toString method?</p>
  
  <p>Yes, I know, I could also send prefix to nodejs, but this is not really a nice solution, and sometimes formatting function can depend on many variables which are in the scope where function is defined.</p>
  
  <p><em>Yes, I know I shouldn't be using eval</em></p>