Le comportement de "this" lorsque la fonction bar
est appelée me déroute. Voir le code ci-dessous. Est-il possible de faire en sorte que "this" soit une ancienne instance d'objet js lorsque bar est appelé à partir d'un gestionnaire de clic, au lieu d'être l'élément html?jQuery/JavaScript "this" confusion du pointeur
// a class with a method
function foo() {
this.bar(); // when called here, "this" is the foo instance
var barf = this.bar;
barf(); // when called here, "this" is the global object
// when called from a click, "this" is the html element
$("#thing").after($("<div>click me</div>").click(barf));
}
foo.prototype.bar = function() {
alert(this);
}
Veuillez expliquer le '' ceci "est l'instance de foo'. Le fichier jsfiddle suivant (http://jsfiddle.net/yY6fp/1/) montre que 'this' dans' this.bar() 'est évalué à l'objet' window' (global). –