开发者

javascript 'this' scope in jQuery

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, fu开发者_运维知识库nction() {
    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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜