javascript - 与 jquery 中的 'this' 关键字混淆

标签 javascript jquery function object

请帮忙,我无法弄清楚。

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')

提前感谢您的帮助

最佳答案

有效的原因是 tour.el.data('location') 是从 fetchPhotos 调用的。

只要你愿意

new Tour().fetchPhotos();

而不是

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

替换将起作用。

但是在做

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

就像后者。它的工作原理不一样。

关于javascript - 与 jquery 中的 'this' 关键字混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19900256/

相关文章:

javascript - 如何从 php 调用 javascript 函数

javascript - 条件验证问题

javascript - 如何使用 JavaScript(或 jQuery)使元素的内容可编辑

javascript for 循环和函数

python - 逐元素乘以 2D NumPy 数组并求和

c# - 在c#中多次运行RegisterStartupScript

javascript - Vue + Jest 全局配置转移到规范文件中

c# - 为什么 jQuery 不能管理这个 JSON?

wordpress - 将默认 wordpress 查询更改为 orderby 标题

javascript - 为什么 ng-class-even 需要额外的引号