How to convert a function definition as string to code in JavaScript


Just a snippet for converting a function as string to code:




<!doctype html>
    <meta charset=”utf-8″ />
    <meta http-equiv=”x-ua-compatible” content=”ie=edge”>
    <meta name=”description” content=”A page to quickly spike some code or styling.”>
    <meta name=”viewport” content=”width=device-width, initial-scale=1″>
    <link rel=”icon” href=”data:;base64,iVBORw0KGgo=”>   
        // Define a function as a string.
        // Don’t forget the “(” and the “)” arround the function.
        // See:
        var functionAsString = “(function(a, b){ return a + b; })”;

        // Convert a string containing a function definition to a real function.
        var fn = eval(functionAsString);

        // Execute the created function.
        var result = fn(1, 2);

        // Log result is: 3

Leave a Reply

Your email address will not be published. Required fields are marked *