Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert objects and functions to valid JavaScript source code?

I have a JavaScript object that looks something like this:

{ bacon: [Function], hello: [Function], tables: [Function] }

Where [Function] is an actual JavaScript function.

I want to write this to a .js file with contents like:

var Templates = /*source code here*/

How can I get the source code for the object and function properties as a string, such that eval'ing this "source code string" will give me back the same object?

like image 597
mpen Avatar asked Apr 03 '13 02:04

mpen


3 Answers

I rolled my own serializer:

var templates = { /* object to stringify */ };
var properties = [];
_.each(templates, function(value, key) {
    properties.push(JSON.stringify(key)+': '+value.toString());
});
var sourceCode = 'var Templates = {' + properties.join(",\n") +'};';

This gives me back:

var Templates = {"bacon": function anonymous(locals, attrs, escape, rethrow, merge) { ... },
"hello": function anonymous(locals, attrs, escape, rethrow, merge) { ... },
"tables": function anonymous(locals, attrs, escape, rethrow, merge) { ... }
};

(snipped bodies for brevity)

like image 118
mpen Avatar answered Oct 21 '22 05:10

mpen


In Javascript a function is an object. The Function object supports the method toString(). This will actually give you the source code of a function. Like this:

function foo() {
    var a = 1 + 1;
}

alert(foo.toString()); // will give you the above definition
like image 36
hek2mgl Avatar answered Oct 21 '22 06:10

hek2mgl


If I understand what you're trying to say, this would show me the function code:

myObj = {

    myMethod: function() {
        console.log("This is my function");
    }
}

console.log(myObj.myMethod.toString());
like image 1
Sethen Avatar answered Oct 21 '22 05:10

Sethen