简体   繁体   中英

javascript : save function to object

I saved a function in an Object.

var obj = {
  name: 'bob',
  getName: function() {
    return this.name;
  }
};
console.log(obj.getName());

It shows 'bob'. But when I saved this obj to Session or MongoDB, the function was disappeared.

Session.set('tmp', obj);
var tmpObj = Session.get('tmp');
console.log(tmpObj.getName());

This shows undefined.

I've tested JSON.stringify / parse also, it doesn't work.

How can I keep the function in the object?

In most contexts you cannot save functions. Try putting all variables into primitive properties instead, and after reloading the "dumb" object, reinitialize with methods like this:

var ObjMaker = function(attrs){
  this.name = attrs.name;
}

ObjMaker.greet = function(){
  return 'Hello ' + this.name;
}

var reloadedObj = { name: 'bob' };

var obj = new Obj(reloadedObj);

console.log(obj.greet());

In most cases it is not possible. Technically you can serialize a function using obj.getName.toString() , which should return

function() {
    return this.name;
}

You could then run it with something like eval("(" + functionString + ")()") . But this pretty much always a bad idea.

If you want to store it into MongoDB, you probably want to use Mongoose ODM , and custom setter . This allows you to define a function on a Schema that describes objects stored in MongoDB, which should fulfill your needs.

var objSchema = new Schema({
  name: {
    type: String,
    get: function(name) {
      return name; //Of course, you could manipulate this more if you want.
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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