Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  99] [ 5]  / answers: 1 / hits: 24779  / 14 Years ago, sat, august 28, 2010, 12:00:00

I'm having difficulty referencing this from within a javascript inline function, within an object method.



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

}

}


How do I access this.testVariable from within the submit function?
I'm also using jQuery as well, if that makes a difference.



I wonder if this is the best approach - and maybe I should have submit as a separate function, and then reference that inline, like:



 init : function(){

this.testObject.submit = this.submitForm;

},
submitForm : function(){
// do validation here
console.log(this.testVariable) // outputs testvariable

.
.
.

return valid;
}


But this didn't seem to work either - and I think I'd just like to keep the submit function inline within my init method for now.


More From » function

 Answers
28

A common way is to assign the this you want to a local variable.



init: function() {
var _this = this;
this.testObject.submit(function() {
console.log(_this.testVariable); // outputs testVariable
});
}

[#95773] Thursday, August 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;