What is the correct way to "serialize" functions in javascript for later use

Viewed 12723

I have a "library" of objects that I want to load on the fly from a database. Each object comes with its own special functions that are called at specific times depending on the objects type. Ideally I'd like to be able to do this, although its been pointed out that this doesn't work:

library = {
  "myObj" : {"name" : "myObj", "type" : "myType", "function" : function () { } } //, etc
}

The string "myObj" is passed around my program quite a bit, but I only have to access certain values of the object at a time, and in some circumstances there's a specific function that needs to be run. The problem is that I'm looking at hundreds, and eventually thousands, of potential objects that could exist with varying functions.

What is the "right" way to store a function to be called like this. I know that calling eval can be very unsafe during execution, enabling xss attacks and whatnot. I really want to avoid a massive switch statement or the bloated loading of additional functions. I'd also like the solution to be as concise as possible.

This can't be the first time this has come up. ;/

Thanks for your help.

7 Answers

You can only really serialise a whole file with require calls in it. If you do that, you can create a module, exports and module.exports, eval the file with a function surrounding it and snag the module.exports out of it.

It's not exactly secure, but for that you need to use something like VM2 and value-censorship (which I've been working on) to avoid them calling eval() and owning your machine or the entire network.

There is no right way to do this, because its not generally a good idea.

HOWEVER, if you want to do it anyways you can simply extend the prototype of Function with a .toJSON method.

Function.prototype.toJSON = function(){ return this.toString(); }

Then you can simply use JSON.stringify and functions will be serialized as strings.

Its generally a not good idea in most cases. There are very few circumstances where you want to do this and even then, there is probably a better way.

Related