variable JavaScript (de Node.js) non accessible sur appel de la fonction intérieure. now.js
-
22-10-2019 - |
Question
J'utilise now.js et Mongoose dans un projet de nœud et ne parviens pas à accéder à l'objet this.now à l'intérieur d'une fonction mangouste. Par exemple.
everyone.now.joinDoc = function (project_id){
this.now.talk(); //this will work
Project.findOne({'_id':project_id}, function(err, project){
if(project){
this.now.talk(); // this will not work "TypeError: Cannot call method 'bark' of undefined"
};
});
};
La solution
Modifier le code à ceci:
everyone.now.joinDoc = function (project_id){
this.now.talk(); // this will work
var that = this; // save 'this' to something else so it will be available when 'this' has been changed
Project.findOne({'_id':project_id}, function(err, project){
if(project){
that.now.talk(); // use local variable 'that' which hasn't been changed
};
});
};
L'intérieur de votre fonction intérieure, la this
est probablement être mis à autre chose. Donc, pour préserver la valeur que vous souhaitez accéder, vous attribuez à une autre variable locale qui sera disponible dans la fonction intérieure.
Autres conseils
everyone.now.joinDoc = function (project_id){
this.now.talk(); // this will work
Project.findOne({'_id':project_id}, (function(tunnel, err, project){
if(project){
this.now.talk();
};
}).bind(this, "tunnel")); // overwrite `this` in callback to refer to correct `this`
};
Utilisez Function.prototype.bind
pour définir la valeur de this
à la valeur que vous voulez
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow