How to convert String to Function prototype in JS?

261 views Asked by At

So I have a js object with the following sample key-value pairs.

var serial = { 
 open: function(a, b) { 
       do something..
},

close: function (a,b) { 
       do something
}

}

As seen above the value for the keys are js functions. Due to some requirements I had to convert the whole object to string. I had used the following code to convert it to string:

var json = JSON.stringify(window.serial, function(key, value) {
    if (typeof value === 'function') {
        return value.toString();
    } else {
        return value;
    }   
});

How can I convert the strings back to function prototypes and store it in the same obj?

1

There are 1 answers

3
Akash Shrivastava On

eval will convert string back to function

var str = "function fn(){ console.log('loggin function') }";

eval(str);

fn();