Tutorial :In jQuery, how do you resolve the scope of “this”, when you are in the scope of each()?



Question:

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?


Solution:1

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


Solution:2

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")));    });        }  


Solution:3

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.


Solution:4

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 :)


Solution:5

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"));          });      };  }  


Solution:6

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »