Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - Using JSON.stringify on custom class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...