【问题标题】:confuse with 'this' keyword in jquery与 jquery 中的“this”关键字混淆
【发布时间】:2013-11-11 06:36:25
【问题描述】:

请帮忙,我想不通。

function Tour(el) {
  var tour = this;
  this.el = el;
  this.fetchPhotos = function() { 
    $.ajax('/photos.html', {
      data: {location: tour.el.data('location')},
      context: tour,
      success: function(response) {
        this.el.find('.photos').html(response).fadeIn();
      },
      error: function() {
        this.el.find('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
      },
      timeout: 3000,
      beforeSend: function() {
        this.el.addClass('is-fetching');
      },
      complete: function() {
        this.el.removeClass('is-fetching');
      }
    });
  }
  this.el.on('click', 'button', this.fetchPhotos);
}
$(document).ready(function() { 
  var paris = new Tour($('#paris'));
});

在上面的函数中,我知道context: tourthis.fetchPhotos 函数中设置this 来引用Tour。所以我的问题是为什么这部分代码tour.el.data('location')可以改成this.el.data('location')

感谢您的帮助

【问题讨论】:

  • 阅读this
  • 您在$.ajax 中丢失了this 的上下文,在$.ajax 之外声明为不同的变量

标签: javascript jquery function object


【解决方案1】:

之所以有效是因为tour.el.data('location') 是从fetchPhotos 调用的。

只要你愿意

new Tour().fetchPhotos();

而不是

var f = new Tour().fetchPhotos;
f();

替换将起作用。

但是做

this.el.on('click', 'button', this.fetchPhotos);

就像后者。它不一样。

【讨论】:

  • 扩展一点:一个经验法则是,当函数被调用时,上下文就是点左侧的任何内容。 this.fetchPhotos 没有调用该方法,而是可以想象它会像这样发生:var callback = arguments[2]; callback.call(that, args); where that === el
  • @Derija93,很好地解释了一个经常解释不清的概念。
【解决方案2】:

正如 charlietfl 所写,这是 ajax 回调中的不同上下文,您必须在 ajax 调用之前将 this 缓存到任何变量并使用该变量。就像你在 tour 变量中所做的那样:

function Tour(el) {
  var tour = this;
  this.el = el;
  this.fetchPhotos = function() { 
    $.ajax('/photos.html', {
      data: {location: tour.el.data('location')},
      context: tour,
      success: function(response) {
        tour.el.find('.photos').html(response).fadeIn();
      },
      error: function() {
        tour.el.find('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
      },
      timeout: 3000,
      beforeSend: function() {
        tour.el.addClass('is-fetching');
      },
      complete: function() {
        tour.el.removeClass('is-fetching');
      }
    });
  }
  this.el.on('click', 'button', this.fetchPhotos);
}
$(document).ready(function() { 
  var paris = new Tour($('#paris'));
});

在 ajax 调用之外(如 click 事件绑定器)可以使用 this,但在那些回调函数中,它指的是回调处理程序

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 2011-10-19
    • 2018-04-22
    • 1970-01-01
    • 2016-02-25
    • 2019-11-18
    • 2010-10-17
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多