javascript “这个” jQuery 中的范围

发布于 2024-11-08 02:48:33 字数 422 浏览 0 评论 0 原文

我刚刚将一段对象字面量的代码转换为类,并且在 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?
  }) 
}

我想知道如何从每个类中访问类上下文?

我知道我可以在循环之外定义一个变量,但这是首选方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

极致的悲 2024-11-15 02:48:33

在 jQuery each 中,this 关键字引用迭代中的当前元素。
您可以阅读文档并查看示例来说明这一点。

在循环外定义变量是常见情况,例如,在 jQuery-日期选择器的 UI 源代码

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.

心凉 2024-11-15 02:48:33

你已经做到的方式就是你要走的路;一旦您进入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.

幽蝶幻影 2024-11-15 02:48:33

这并不能直接回答您的问题,但我发现最近的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文