qodeninja
qodeninja

Reputation: 11286

In jQuery, how do you resolve the scope of "this", when you are in the scope of each()?

I've created an Object, and have a method setup() in the object.

this.debug = function (){...}

this.setup = function(){    

  var fieldsets = form.children("fieldset");

  fieldsets.each(function(){        
    this.debug($(this).attr("class")));
  });


}

I'm trying to call this.debug which is in the scope of the Object but not in the scope of each, since THIS is a different this...

How do I access this.debug?

Upvotes: 2

Views: 1859

Answers (6)

Skilldrick
Skilldrick

Reputation: 70869

Say var that = this after this.debug, then do that.debug.

Upvotes: 5

gnarf
gnarf

Reputation: 106392

This is basically Skilldrik's answer, but showing you where it works best

this.setup = function(){    
  // save it in a scoped var...  some people use "self" for this purpose, i prefer
  // naming it whatever the outer object actually is...
  var containingObject = this;

  var fieldsets = form.children("fieldset");

  fieldsets.each(function(){        
    // use that scoped var later!
    containingObject.debug($(this).attr("class")));
  });      
}

Upvotes: 3

Svante Svenson
Svante Svenson

Reputation: 12478

this.debug = function (){...}

this.setup = function(){    
  var that = this;
  var fieldsets = form.children("fieldset");

  fieldsets.each(function(){        
    that.debug($(this).attr("class")));
  });


}

Upvotes: 0

theahuramazda
theahuramazda

Reputation: 441

I normally do it this way: (note:example below is from memory but looks sound):

function CustomObject()
{
  var _instance = this;

  this.debug = function(){...};
  this.setup =
    function()
    {    
      var fieldsets = form.children("fieldset");
      fieldsets.each(
        function()
        {        
          _instance.debug($(this).attr("class"));
        });
    };
}

Upvotes: 0

mana
mana

Reputation: 6547

I tried this in my Greasemonkey-Console:

this.debug = function() {
    console.log("foo");
};

this.setup = function() {

    var fieldsets = form.children("fieldset");

    fieldsets.each(function(){
        debug($(this).attr("class"));
    });
};

Which will search the scope for any debug .. which that is hopefully the function above. This will fail, if you assign a variable with the very same name :)

Upvotes: 0

Scharrels
Scharrels

Reputation: 3065

In jQuery 1.4 you can do:

this.debug = function (){...}

this.setup = function(){    

  var fieldsets = form.children("fieldset");

  fieldsets.each(jQuery.proxy(function(){
    this.debug($(this).attr("class")));
  },this);
}

The jQuery.proxy(function, object) function will take 2 arguments:

  • The function will be the function used in the loop.
  • The object argument will be the this object inside the function.

In this way, you can transfer the this from the outer scope inside the each function.

Upvotes: 1

Related Questions