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?
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
As I said in my comment, you have to keep a reference inside the function:
validate: function(theForm) {
var self = this;
$('input, textarea', theForm).each(function() {
var valueLength = $(this).val().length;
if (valueLength === 0) {
$(this).addClass('invalid');
self.listenForInput($(this));
}
});
},
You are passing a function to each. Inside this callback, this refers to the DOM element. That's why you pass it to jQuery ($(this)) to be able to call jQuery methods on that element. It cannot refer to formObj too!
What this refers to is determined by how a function is called and each function has its own this (the Mozilla documention describes this in more detail).
If you call validate with formObj.validate(), then this refers to formObj.
The jQuery documentation for each states:
More importantly, the callback is fired in the context of the current DOM element, so the keyword
thisrefers to the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With