将对象和函数转换为有效的JavaScript源代码?
我有一个JavaScript对象,看起来像这样:
{ bacon: [Function], hello: [Function], tables: [Function] }
其中[Function]
是一个实际的JavaScript函数。
我想把它写到一个.js
文件中,内容如下:
var Templates = /*source code here*/
我怎样才能得到的对象和函数属性的源代码作为一个string,这样评价这个“源代码string”会让我回到同一个对象?
我推出了我自己的序列化器:
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") +'};';
这让我回想起:
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) { ... } };
(为了简洁,剪掉身体)
在Javascript中,函数是一个对象。 Function
对象支持toString()
方法。 这实际上会给你一个函数的源代码。 喜欢这个:
function foo() { var a = 1 + 1; } alert(foo.toString()); // will give you the above definition
如果我明白你想说什么,这将显示function代码:
myObj = { myMethod: function() { console.log("This is my function"); } } console.log(myObj.myMethod.toString());
您可以使用JSON.stringify通过replacer
参数完成此操作:
var myObj = { a : 1, b : function(val) { doStuff(); }; var replacer = function(key, val) { return "key : " + val.toString(); }; console.log(JSON.stringify(myObj, replacer));
我还没有testing过,但这个想法应该是健全的。
如果你想使用node.js,你可以使用一个可以处理AST的库。 你可以看看https://github.com/substack/node-falafel