0

I have just converted an piece of code that was an object literal to a class and am having problems with the scope in a jQuery $.each() loop.

Say I have a class...

var myClass = function(var1) {
  this.var1 = var1;
}

myClass.prototype.myFuncion = function() {
  var context = this;
  $.each(this.var1, function() {
    context.myOtherFunction()

    //is there any way of accessing 'this' from here?
  }) 
}

I want to know how to access the class context from within the each?

I know I can define a variable outside of the loop but is this the preferred method?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tim
  • 2,235
  • 4
  • 23
  • 28
  • I've listed a few ways in this [answer](http://stackoverflow.com/questions/3349380/jquery-proxy-usage/3349438#3349438). – Anurag May 18 '11 at 03:22

3 Answers3

1

In jQuery each, the this keyword refers to the current element in the iteration. You can read the documentation and see examples to illustrate this.

Defining a variable outside the loop is common case, as you can see, for instance, in jQuery-UI source code for datepicker.

marcosfromero
  • 2,853
  • 17
  • 17
1

The way you've done it is the way to go; as soon as you enter the scope of the each, "this" refers to the current item in the collection which is being eached. As far as I know there is no internal language construct to get the 'parent' this; renaming it is the best way.

Jeremy Warne
  • 3,437
  • 2
  • 30
  • 28
0

This doesn't directly answer your question, but I found this recent Google I/O video extremely useful: http://ontwik.com/javascript/google-io-2011-learning-to-love-javascript

About 20-25 minutes in is an excellent explanation of 'this' in JavaScript. It also very clearly explains some of the language idiosyncrasies.

Christopher
  • 1,723
  • 1
  • 18
  • 31