Tengo dificultades para hacer referencia a "esto" desde una función en línea de JavaScript, dentro de un método de objeto.Accediendo a esto desde la función en línea de un objeto
var testObject = {
oThis : this,
testVariable : "somestring",
init : function(){
console.log(this.testVariable); // outputs testVariable as expected
this.testObject.submit(function(){
var anotherThis = this;
console.log(this.testVariable) // undefined
console.log(oThis.testVariable) // undefined
console.log(testObject.testVariable) // outputs testVariable
console.log(anotherThis.testVariable) // undefined
}
}
Cómo accedo this.testVariable
desde dentro de la función de enviar? También estoy usando jQuery, si eso hace la diferencia.
Me pregunto si este es el mejor enfoque - y tal vez debería haber presentar como una función separada, y después hacer referencia a que en línea, como:
init : function(){
this.testObject.submit = this.submitForm;
},
submitForm : function(){
// do validation here
console.log(this.testVariable) // outputs testvariable
.
.
.
return valid;
}
pero esto no parece funcionar bien - y Creo que me gustaría mantener la función de envío en línea dentro de mi método init
por el momento.
posible duplicado de [¿Por qué este cierre no tiene acceso a la palabra clave 'this'? - jQuery] (http://stackoverflow.com/questions/3323189/why-doesnt-this-closure-have-access-to-the-this-keyword-jquery) –