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?
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)
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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With