javascript 'this' scope in jQuery

痞子三分冷 提交于 2020-01-06 08:46:13

问题


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:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6039487/javascript-this-scope-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!