Convert objects and functions to valid JavaScript source code?

收藏待读

http://www.nodejsrecipes.com/recipes/15777895/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?

Problem courtesy of: mpen

Solution

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)

Solution courtesy of: mpen

Discussion

If you may want to use node.js , you can use a lib that can handle ASTs. You may have a look at https://github.com/substack/node-falafel

Discussion courtesy of: framlin

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());

Discussion courtesy of: Sethen

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

Discussion courtesy of: hek2mgl

You can use JSON.stringify to accomplish this via the replacer argument:

var myObj = { a  : 1, b : function(val) { doStuff(); };

var replacer = function(key, val) {
      return "key : " + val.toString();
};

console.log(JSON.stringify(myObj, replacer));

I haven’t tested this but the idea should be sound.

Discussion courtesy of: Chris Hayes

This recipe can be found in it’s original form on Stack Over Flow .

相關閱讀

免责声明:本文内容来源于Node.js Recipes,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。