Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method from another method within the same object in JavaScript?

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
like image 791
Pam Avatar asked Aug 23 '11 00:08

Pam


1 Answers

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 this refers to the element.

like image 126
Felix Kling Avatar answered Oct 20 '22 06:10

Felix Kling