I’m creating a small lib to interact with MongoLab HTTP API, but I’m having some issues. I’m using CommonJS modules.
I have a Model object, made to behave as prototype for the other models:
module.exports = {
//[...]
//this will be overriden by the other models
fields: ['id'],
setFields: function(values) {
_.each(this.fields, function(field) {
this[field] = values[field]
})
}
}
And I have, for example, an User model:
var Model = require('models/Model')
function User (properties) {
this.fields = [
'id',
'name',
'surname',
'email',
'password'
]
this.setFields(properties)
//[...]
}
There, the setFields() call works correctly, iterating through each of the five fields given in the User model; although, it won’t set the User properties. If I add a console.log(this.name) before the end of the setFields() definition, it will give me undefined. The only way I got to workaround the issue was passing the this object as argument for the setFields method, and using the argument instead of this.
It looks like a scope problem for me, but I’m still quite new with JavaScript OO, so… What’s wrong with my logic?
You need to provide a
contextparameter to_.eachto set thethiscontext you’re expecting in your callback function: