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?

1
  • I've listed a few ways in this answer. Commented May 18, 2011 at 3:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.