简体   繁体   English

javascript:将函数保存到对象

[英]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'. 它显示“ bob”。 But when I saved this obj to Session or MongoDB, the function was disappeared. 但是,当我将此obj保存到Session或MongoDB时,该功能消失了。

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. 我也测试了JSON.stringify / parse,它不起作用。

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 从技术上讲,您可以使用obj.getName.toString()序列化一个函数,该函数应返回

function() {
    return this.name;
}

You could then run it with something like eval("(" + functionString + ")()") . 然后,您可以使用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 . 如果要将其存储到MongoDB中,则可能要使用Mongoose ODM和custom setter This allows you to define a function on a Schema that describes objects stored in MongoDB, which should fulfill your needs. 这使您可以在Schema上定义一个函数,该函数描述应该存储在MongoDB中的对象,这些函数应该可以满足您的需求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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