gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:11:01 25 4
gpt4 key购买 nike

请帮忙,我无法弄清楚。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com