javascript “这个” jQuery 中的范围
我刚刚将一段对象字面量的代码转换为类,并且在 jQuery $.each()
循环中遇到范围问题。
假设我有一个类...
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?
})
}
我想知道如何从每个类中访问类上下文?
我知道我可以在循环之外定义一个变量,但这是首选方法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 jQuery
each
中,this
关键字引用迭代中的当前元素。您可以阅读文档并查看示例来说明这一点。
在循环外定义变量是常见情况,例如,在 jQuery-日期选择器的 UI 源代码。
In jQuery
each
, thethis
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.
你已经做到的方式就是你要走的路;一旦您进入each的范围,“this”就指的是正在each的集合中的当前项目。据我所知,没有内部语言构造可以获取“父”this;重命名是最好的方法。
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.
这并不能直接回答您的问题,但我发现最近的 Google I/O 视频非常有用:http://ontwik.com/javascript/google-io-2011-learning-to-love-javascript
大约 20-25 分钟是对 JavaScript 中“this”的精彩解释。它还非常清楚地解释了一些语言特性。
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.