Sorry the title couldn't be more specific. I do this in Javascript sometimes to 'attach' a variable to an anonymous function but I'm not sure of the vocabulary so I don't know how to study more about it or see if what I'm doing is optimal.
I'm using MEAN stack with Mongoose to create a getter function on every member of the schemas.
testPlugin.plugin = function(schema, options){
schema.set('toObject', { getters: true });
schema.set('toJSON', { getters: true });
// Simple counter
let i = 0;
schema.eachPath((path, type) => {
/* Add a *different* getter to each member with a different value of `i` */
type.getters.push(((i, type)=>{
return function(value){
console.log(i + ": " + path + ": " + type);
return value;
}
})(i, type));
i++;
});
}
Basically if I were to just pass 'i' to the function and there were 5 members, all of the functions would trace something like
'5: path.path: String'
'5: path.path: Integer'
'5: path.path: ObjectID'
'5: path.path: String'
Instead of having the value 'stored' as it were in the function which, when executed on a schema would trace out something like
'1: patha: String'
'2: pathint: Integer'
'3: _id: ObjectID'
'4: path.path: String'
So instead I'm returning a new, separate function each time by returning a function from an auto-executed parent function... is this correct or am I going overkill here?
Again, just really looking for the name of this pattern or what pattern I should be using. I saw something similar to this but I forgot.
Aucun commentaire:
Enregistrer un commentaire