Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  195] [ 5]  / answers: 1 / hits: 37581  / 12 Years ago, tue, november 27, 2012, 12:00:00

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


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'


How can I get foo when calling parsedObj.getAttr()?



Thank you in advance!



EDIT



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.


More From » json

 Answers
7

First, you are not defining a class.



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



Which will be stripped off when using JSON.stringify.



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



Here is an example:



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


which will output:



true foo

[#81772] Monday, November 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alorac

Total Points: 262
Total Questions: 82
Total Answers: 97

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
alorac questions
Sat, Oct 10, 20, 00:00, 4 Years ago
Tue, Sep 22, 20, 00:00, 4 Years ago
Wed, Jul 1, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Sun, May 17, 20, 00:00, 4 Years ago
;