Cannot read Property 'query' of Undefined

Asked

Viewed 694 times

1

The mistake Cannot read property 'query' of undefined is reported when trying to save data to the database. However, the Property query works for getNews. Ex:

function NewsDAO(database){
    this._database = database;
}

NewsDAO.prototype.getNews = function(callback){
    this._database.query('SELECT * FROM news', callback);
}
NewsDAO.prototype.saveNotice = (notice, callback) =>{
    this._database.query('INSERT INTO noticias SET ?', notice, callback);
    console.log(this._database);
}

module.exports = () => {
    return NewsDAO;
}

When I give a console.log in the _database in the method getNews(), I can see all properties. When I do the same on saveNotice(), returns a undefined. What could be?

1 answer

4


The expression lambda, called arrow function in Javascript, it is not just a reduced way of writing a function, another feature of it is not to do the bind in the instance in which it is being invoked, i.e., in a lambda expression, the this does not refer to the object in which it was declared.

Thus declaring, this will refer to the higher scope of the object, i.e. this will be the window (or the module itself in the case of Nodejs):

NewsDAO.prototype.saveNotice = (notice, callback) => {
    console.log(this);
}

Now if you declare the function as the expression function, this will refer to the object and the function will work the way you want it to:

NewsDAO.prototype.saveNotice = function(notice, callback) {
    console.log(this);
}
  • It worked super well! Thanks for the clarifications.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.