Andrea D
Andrea D

Reputation: 97

expressjs modify/add a object proprerty in module

I create this module on express:

module.exports = {
 myobj : {},
 myfun : function(app) {

  app.all('/',function (req, res, next) {
   this.myobj.foo = ‘bar’;
  }
 }
}

But it doesn’t works, I received the following error : Cannot set property ‘foo’ of undefined

But I if I do this,This works well, why ?:

module.exports = {
 myobj : ‘’,
 myfun : function(app) {
 app.all('/',function (req, res, next) {
   this.myobj = ‘bar’;
  }
 }
}

I don’t understand why I can’t add a property to my object (first case) but I can modify my var myobj (second case).

What’s wrong ?

Thanks !

Upvotes: 1

Views: 26

Answers (1)

kaxi1993
kaxi1993

Reputation: 4710

Try this code:

module.exports = {
 myobj : {},
 myfun : function(app) {
  var that = this;
  app.all('/',function (req, res, next) {
   that.myobj.foo = ‘bar’;
  }
 }
}

In first case: this references to callback function: function(req, res, next){} not to the object you are exporting, because of this myobj is undefined and you receive error while trying to access foo property of undefined object.

In second case: you initialize new property myobj of function(req, res, next) {} callback and it's ok, you can do it, but if you call myfun and then check myobj will see that it is still empty string this happens because you modify callback function property not exported object.

Upvotes: 1

Related Questions