Pergunta

I am trying to create a small library that you can send an object(that has functions) and some data, and args, and it will send the object, data, and args to a worker process who will then eval the object to reconstruct the functions(from strings to functions)

Currently I have this:

JSON.stringify(object, function(key, val) { if typeof val === 'function' { return val + '' } return val });

This function will stringify an object including functions.

In my worker I am trying to undo this process.

I have tried the following: eval(object) I have also tried implementing JSON.parse with trying to eval() each function when I come across one.

I have also tried eval("return " + object.function)

Is this possible?

Foi útil?

Solução

You probably want:

eval("(" + object.function + ")");

You cannot put a return statement just somewhere.

function() {} is evaluated as a function declaration, which fails because it has no name. Since the data to be parsed represents a function expression, like var f = function() {}, you need to put () around it, so that it is evaluated as an expression.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top