Esta pregunta no es específico de jQuery, pero adaptadas a JavaScript en general. El problema principal es cómo "canalizar" una variable en funciones incorporadas. Este es el ejemplo:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
Esta técnica se basa en el uso de un cierre. Pero no funciona con this
porque this
es una variable que puede cambiar seudo ámbito de alcance de forma dinámica:
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
¿Qué podemos hacer? Asignarla a alguna variable y utilizarlo a través del alias:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
no es único en este sentido: arguments
es la otra variable de pseudo que debe ser tratada de la misma manera — por aliasing.
Debe evitar 'self' ya que hay un objeto' window.self' y usted podría terminar con que accidentalmente si se olvida de declarar su propio 'self' var (por ejemplo, cuando se mueve alrededor de un poco de código). Esto puede ser molesto de detectar/depurar. Es mejor usar algo como '_this'. –
relacionado: [¿Qué var que = esto; significa en javascript?] (http://stackoverflow.com/q/4886632/1048572) – Bergi
Del [JavaScript Tutorial] (http://javascript.info/tutorial/this): "El valor de' this' es dinámico en JavaScript. Se determina cuando la función * se llama *, no cuando se declara ". – DavidRR