在jQuery函数中使用"this"

Zen*_*g74 1 jquery this jquery-blockui

我创建了一个CalendarViewerPortlet自定义对象JS对象.在这个对象中,我存储的东西,如portlet的id和它的上下文路径.该对象还有许多自定义方法,一些用于获取/设置成员变量,一些用于执行特定的操作.

当我尝试使用"this"引用对象的功能时.在jQuery函数内部,它会爆炸.我知道在这个上下文中的术语"this"可能指的是其他东西,但我不知道如何绕过这个问题并让它引用该对象,就像我想要的那样.

这是违规代码:

jQuery.ajax({
  url: jQuery(formSel).attr("action"), 
  type: "POST", 
  data: jQuery(formSel).serialize(), 
  beforeSend: function(xhr) {
  jQuery(msgSel).hide();
  jQuery(msgSel).html("");
  jQuery(tableSel).hide();
  jQuery(pagerSel).hide();
  jQuery(cpSelector).block({
  message: "<img src='"+this.getContextPath()+"/images/icon_loading.gif' align='absmiddle' alt='Loading...' /> Fetching events..."
  });
},
Run Code Online (Sandbox Code Playgroud)

注意"this.getContextPath()".这就是代码失败的地方.我试图引用我的自定义对象的getContextPath()函数.我怎样才能做到这一点?

Mar*_*amy 6

问题是代码this.getContextPath()稍后在作为ajax()函数的on选项传递的匿名函数中执行.因此,您想要的'this'(您的自定义JS对象)在执行方法时将无法使用.您可以将其存储在变量中,并将函数"closure"作为引用.以下应该有效:

var calendarViewer = this;

jQuery.ajax({
  url: jQuery(formSel).attr("action"), 
  type: "POST", 
  data: jQuery(formSel).serialize(), 
  beforeSend: function(xhr) {
  jQuery(msgSel).hide();
  jQuery(msgSel).html("");
  jQuery(tableSel).hide();
  jQuery(pagerSel).hide();
  jQuery(cpSelector).block({
  message: "<img src='"+calendarViewer.getContextPath()+"/images/icon_loading.gif' align='absmiddle' alt='Loading...' /> Fetching events..."
  });
},
Run Code Online (Sandbox Code Playgroud)