I'm just getting started in OO javascript so please bear with me.
This works:
var myObj = {
foo : function() {
alert('hello');
this.bar();
},
bar: function() {
alert('world');
}
}
However if I do some other stuff after the hello alert in the "foo" method then the meaning of "this" changes from the object to whatever I last selected so using this.bar() doesn't execute the other method in the class.
So I tried to cache "this" in a variable like so:
var myObj = {
publicVars: {
theObj : this
},
foo : function() {
alert('hello');
publicVars.theObj.bar();
},
bar: function() {
alert('world');
}
}
But that didn't work either. So what is the solution?
EDIT
Here is my actual code:
var formObj = {
validate : function(theForm) {
$('input, textarea', theForm).each(function() {
var valueLength = $(this).val().length;
if (valueLength === 0) {
$(this).addClass('invalid');
this.listenForInput($(this)); // <!------- this isn't working
}
});
},
listenForInput : function(theField) {
// theField.keyup(function() {
// if ($(this).val().length > 0) {
// theField.removeClass('invalid');
// }
// });
alert('I work!!!!');
}
} // end obj
thiswill refer towindow(most likely). In this case you just have to create a reference tothisinsidefoofirst.thisto refer to yourformObj, and the DOM element at the same time. That's just not going to happen.this.listenForInput($(this));