简体   繁体   English

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

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

I have a JavaScript object that looks something like this: 我有一个看起来像这样的JavaScript对象:

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

Where [Function] is an actual JavaScript function. 其中[Function]是一个实际的JavaScript函数。

I want to write this to a .js file with contents like: 我想把它写成一个.js文件,内容如下:

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. 在Javascript中,函数是一个对象。 The Function object supports the method toString() . Function对象支持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());

You can use JSON.stringify to accomplish this via the replacer argument: 您可以使用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));

I haven't tested this but the idea should be sound. 我没有测试过这个,但这个想法应该是合理的。

If you may want to use node.js, you can use a lib that can handle ASTs. 如果您可能想使用node.js,则可以使用可以处理AST的lib。 You may have a look at https://github.com/substack/node-falafel 您可以查看https://github.com/substack/node-falafel

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

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