我不知道 MongoDB,但是您可以通过将从服务器返回的数据库对象传递给构造函数来轻松地做您想做的事情:
您可以像这样传递对象:
var myObject = new object(MongoDBObj);
然后在您的目标代码中,您可以执行以下操作:
function object(data) {
this.myProp1 = data.Prop1;//from db obj
this.myProp2 = data.Prop2;//from db obj
this.myProp3 = getProp3Calculation(); //from global calculation
[more functions and props for the object]
}
编辑:对于我的第一条评论
你也可以这样做(简单的例子);
function object() {
this.myProp1 = null;
this.myProp2 = null;
this.myProp3 = getProp3Calculation(); //from global calculation
this.init = function([params]){
var that = this;
var data = loadData(params);
//if asynchronous the following code will go into your loadCompletedHandler
//but be sure to reference "that" instead of "this" as "this" will have changed
that.myProp1 = data.Prop1;
that.myProp2 = data.Prop2;
};
[more functions and props for the object]
}
更新 3 - 显示以下讨论结果:
function object() {
this.myProp1 = null;
this.myProp2 = null;
this.myProp3 = getProp3Calculation(); //from global calculation
this.init = function([params], callback){
var that = this;
var model = [Mongoose Schema];
model.findOne({name: value}, function (error, document) {
if (!error && document){
//if asynchronous the following code will go into your loadCompletedHandler
//but be sure to reference "that" instead of "this" as "this" will have changed
that.myProp1 = document.Prop1;
that.myProp2 = document.Prop2;
callback(document, 'Success');
}
else{
callback(null, 'Error retrieving document from DB');
}
});
};
[more functions and props for the object]
}