jQuery中的javascript'this'范围 [英] javascript 'this' scope in jQuery

查看:85
本文介绍了jQuery中的javascript'this'范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将一段代码从对象文字转换为类,并且在jQuery $.each()循环中遇到了作用域问题.

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.

说我上课...

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?

推荐答案

在jQuery each中,this关键字引用迭代中的当前元素. 您可以阅读文档并查看

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.

常见的情况是在循环外定义变量,例如,在jQuery-

Defining a variable outside the loop is common case, as you can see, for instance, in jQuery-UI source code for datepicker.

这篇关于jQuery中的javascript'this'范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆