Bir nesne yönteminde, javascript satır içi işlevinden "bu" ifadesine başvurmakta zorluk çekiyorum.Bir nesnenin satır içi işlevinden buna erişme
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
}
}
nasıl gönderebilirim işlev içinde this.testVariable
erişirim? Ayrıca jQuery de kullanıyorum, bu bir fark yaratırsa. Bu iyi yaklaşım ise
acaba - ve belki daha sonra ayrı bir fonksiyon olarak göndermesini ve gerektiği satır içi başvuru gibi:
init : function(){
this.testObject.submit = this.submitForm;
},
submitForm : function(){
// do validation here
console.log(this.testVariable) // outputs testvariable
.
.
.
return valid;
}
Ama bu işe ya görünmüyordu - ve Şimdilik şimdilik benim init
yöntemimde gönderme işlevini satır içi tutmak istiyorum.
olası kopyası [Neden bu kapanış 'bu' anahtar sözcüğe erişemiyor? - jQuery] (http://stackoverflow.com/questions/3323189/why-doesnt-this-closure-have-access-to-the-this-keyword-jquery) –