繁体   English   中英

将对象和函数转换为有效的JavaScript源代码?

[英]Convert objects and functions to valid JavaScript source code?

我有一个看起来像这样的JavaScript对象:

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

其中[Function]是一个实际的JavaScript函数。

我想把它写成一个.js文件,内容如下:

var Templates = /*source code here*/

如何将对象和函数属性的源代码作为字符串获取,以便评估此“源代码字符串”将返回相同的对象?

我推出了自己的序列化器:

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

如果我理解你想说的话,这会告诉我功能代码:

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

我没有测试过这个,但这个想法应该是合理的。

如果您可能想使用node.js,则可以使用可以处理AST的lib。 您可以查看https://github.com/substack/node-falafel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM