Il comportamento di "questo" quando viene chiamata la funzione bar
mi sconcerta. Guarda il codice qui sotto. C'è un modo per fare in modo che "questo" sia una semplice istanza di vecchio js quando la barra viene chiamata da un gestore di clic, invece di essere l'elemento html?jQuery/JavaScript "questo" confusione puntatore
// 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);
}
Spiega che "questo" è l'istanza di foo. Il seguente jsfiddle (http://jsfiddle.net/yY6fp/1/) dimostra che 'this' in' this.bar() 'valuta l'oggetto' window' (globale). –