未定义NodeJS原型参数

时间:2019-04-17 19:00:02

标签: node.js object prototype

我尝试使用在其他原型函数中创建的数据库模型,但是它始终返回模型未初始化的错误,因此this.model为空。 我的Object总体上有问题,因为我发现的所有解决方案都与原型函数中的“ this”没有问题。

我的节点版本:11.9.0

function CRUD (collection /* String */, schema /* mongoose.Schema */) { 
    this.model = db.model(collection, schema)
    console.log('Model initialized ')
}
CRUD.prototype.create = function (req, res, next) {
   if(!this.model) throw new Error('No Model initialized')
   this.model.create(req.body, (err, data) => {
        if (err){
            res.send('Can`t create Object')
        } else{
            console.log(data, ' created')
            next()
        }

    })
}
CRUD.prototype.read = function (req, res, next) {
    if(!this.model) throw new Error('No Model initialized')
    if(req.query){ // for GET requests
        var filter = req.query
    }else if(req.body){ // for other requests
        var filter = req.body
    }else{
        var filter = {} // no filter
    }
    this.model.find(filter, req.body, (err, data) => {
        if (err){
            res.send('Can`t find Object')
        } else{
            req.body = data
            next()
        }  
    })
}

当我使用代码代替“ this.model”,“ CRUD.prototype.model”时,该代码已经起作用,但是我不得不更改它,因为该模型在原型中是静态参数,并且我需要使用其他模型每个CRUD对象。

1 个答案:

答案 0 :(得分:0)

this由调用函数的方式定义。如果将这些函数作为回调传递给诸如快速路由之类的东西,则会丢失this绑定。您将需要通过类似以下的函数来传递函数:

cConfig = new crud('Config', new db.Schema(schemas.Config))
app.get('/', cConfig.create.bind(cConfig))

这是一个简单的示例,可能有助于显示问题:

function someObj(f_name){
  this.f_name = f_name
}

someObj.prototype.talk = function(){
  console.log(this.f_name)
}

let me = new someObj("mark")
me.talk() // works as expected

/* some function that takes a callback */
function runCB(cb){
  cb()
}

// pass in talk:

runCB(me.talk)          // doesn't work because this binding is lost 
                        // the CB is just passed as a function reference
                        // and so we no longer know it belongs with `me`

runCB(me.talk.bind(me)) // but it works it you hard bind it back
runCB(() => me.talk())  // also works because we call it as me.talk()