This post demonstrates how to convert a JavaScript function to a string and using the same string to declare and execute a new method dynamically.
Using Plunker
Plunker is an online website that allows programmers to create client-side JavaScript code snippets for demonstration, issue replication, or Proofs-of-Concept (POCs).
My Plunker
To access my JavaScript code snippet available on Plunker, please access the following URL:
https://plnkr.co/G4nQ4n50JB1dWF5NCLQu
Notice the contents under the Console tab on the right side. First, the function’s definition is displayed. Then, that definition is used twice displaying “This is myFunction” twice.
There are 2 important files to get things working.
- index.html
- script.js
By the way, I am using Google Chrome to access Plunker.
Using Node.js
Node.js allows you to create and execute server-side codes. We’ll not discuss Node.js but I assume you have it installed in your system.
Download the script.js from my Plunker, and run it on the Windows command-line prompt.
The JavaScript Code Snippet
The script.js file used in both Plunker and Node.js has the following codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 | var myFunction = function() { // Any codes here console.log('This is myFunction'); }; var fString = myFunction.toString(); console.log(fString); var fn = new Function('return ' + fString)(); fn(); fn = Function('return ' + fString)(); fn(); |
Code to Convert a Function to String
To convert a function to string, use the toString() method of a function object.
1 | var fString = myFunction.toString(); |
Codes to convert string to a function
1 2 3 4 5 6 7 8 | // Option 1 var fn = new Function('return ' + fString)(); fn(); // Option 2 fn = Function('return ' + fString)(); fn(); |