在自定义类上使用JSON.stringify [英] Using JSON.stringify on custom class
问题描述
我正在尝试将对象存储在redis中,redis是类的实例,因此具有功能,这是一个示例:
I'm trying to store an object in redis, which is an instance of a class, and thus has functions, here's an example:
function myClass(){
this._attr = "foo";
this.getAttr = function(){
return this._attr;
}
}
有没有一种方法可以将对象与函数一起存储在Redis中?我尝试了JSON.stringify()
,但是仅保留了属性.如何存储函数定义并能够执行以下操作:
Is there a way to store this object in redis, along with the functions? I tried JSON.stringify()
but only the properties are preserved. How can I store the function definitions and be able to perform something like the following:
var myObj = new myClass();
var stringObj = JSON.stringify(myObj);
// store in redis and retreive as stringObj again
var parsedObj = JSON.parse(stringObj);
console.log(myObj.getAttr()); //prints foo
console.log(parsedObj.getAttr()); // prints "Object has no method 'getAttr'"
调用parsedObj.getAttr()
时如何获取foo
?
提前谢谢!
编辑
建议修改MyClass.prototype并存储值,但是类似这样的事情(除setter/getter之外的功能)是
Got a suggestion to modify the MyClass.prototype and store the values, but what about something like this (functions other than setter/getter):
function myClass(){
this._attr = "foo";
this._accessCounts = 0;
this.getAttr = function(){
this._accessCounts++;
return this._attr;
}
this.getCount = function(){
return this._accessCounts;
}
}
我正在尝试说明一个函数,该函数除了执行其他操作外,还可以在每次调用时计算计数或平均值.
I'm trying to illustrate a function that calculates something like a count or an average whenever it is called, apart from doing other stuff.
推荐答案
首先,您没有定义类.
这只是一个对象,其属性的值是一个函数(在创建新的 instance 时,将复制其在构造函数中定义的所有成员函数,这就是为什么说这不是一堂课.)
It's just an object, with a property whose value is a function (All its member functions defined in constructor will be copied when create a new instance, that's why I say it's not a class.)
使用JSON.stringify
时将被剥夺.
考虑使用的是使用V8的node.js,最好的方法是定义一个真实的类,并使用__proto__
播放一些魔术.无论您在类中使用了多少个属性(只要每个属性都使用原始数据类型),该方法就可以正常工作.
Consider you are using node.js which is using V8, the best way is to define a real class, and play a little magic with __proto__
. Which will work fine no matter how many property you used in your class (as long as every property is using primitive data types.)
这里是一个例子:
function MyClass(){
this._attr = "foo";
}
MyClass.prototype = {
getAttr: function(){
return this._attr;
}
};
var myClass = new MyClass();
var json = JSON.stringify(myClass);
var newMyClass = JSON.parse(json);
newMyClass.__proto__ = MyClass.prototype;
console.log(newMyClass instanceof MyClass, newMyClass.getAttr());
它将输出:
true "foo"
这篇关于在自定义类上使用JSON.stringify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!