在JSON上使用节点服务器和Web客户机上的对象方法?

我有一个Javascript库,我想在networking浏览器上使用,也在Node.js后端。 在库中,我有多个对象的方法定义如下:

function foo() { this.bar = 200; this.someMethod = function(baz) { return this.bar + baz; }; } var x = new foo(); 

我可以通过执行以下操作在客户端或Node.js服务器中使用它:

 x.someMethod(5); => (returns 205) 

现在,当我JSON.stringify我的对象,它显示没有方法。

 var string = JSON.stringify(x); => {"bar":200} 

这意味着我不能在我的服务器上解压JSON并使用相同的方法。

 var parsed = JSON.parse(string); document.write(parsed.someMethod(5)); => (doesn't do anything. the methods are gone!) 

在基于类的系统中,我只是使用复制构造函数。 一些可以从JSON重build对象的东西。

 function foo_copy_constructor(parsed_json) { f = new foo(); f.bar = parsed_json.bar; return f; } var z = foo_copy_constructor(parsed); z.someMethod(5); => (returns 205 like it should) 

(jsfiddle: http : //jsfiddle.net/7FdDe/ )

基本上,有没有比这更好的方法?

我的许多对象都包含了我用自己的方法编写的其他对象的实例,这似乎是为每个对象构build一个构造函数,因为客户端和服务器都使用相同的库和对象定义, 我知道JavaScript是基于原型的,但是我并没有真正理解它们,因为我刚刚开始使用JavaScript,习惯于Python和基于类的语言。

感谢您的帮助!

JSON.stringify仅将具有toJSON方法的对象string化。 所以你可以简单地将toJSON方法添加到你的方法中。 (请记住,函数也是对象。)

 function A() { this.method = function() { console.log(1); }; } var c = new A(); JSON.stringify(c); "{}" A.prototype.otherMethod = function() { console.log(1); }; var c = new A(); JSON.stringify(c); "{}" Function.prototype.toJSON = function() { return this.toString(); }; JSON.stringify(c); "{"method":"function () { console.log(1); }"}" 

但是,当parsing这个后面,你得到的函数作为一个string。 所以你必须将string返回到像这样的function:

 var d = JSON.parse(JSON.stringify(c)); Object.keys(d).forEach(function(k) { // If it starts with "function" if (/^function/.test(d[k])) { // Get the body of the function var f = d[k].match(/{(.*)}/).pop(); // Replace the string with a real function d[k] = new Function(f); } }); d.method(); 1 

然而,而不是像这样搞乱JavaScript,我宁愿build议你使用一个经过充分testing的库,如now.js。