"this" 在滑动事件中是 Window,而不是滑动器

"this" in a swiper event is the Window, not the swiper

我有一个带有多个滑块的简单页面。每个滑块由三张幻灯片组成;左、中、右。如果更改了另一个滑块,我想将所有滑块重置到中间。将其想象成 UI,您可以在其中向左或向右滑动以显示可以对列表中的项目执行的操作。我不希望同时显示多个项目的操作 - 因此在一个项目上滑动应该会将所有其他项目重置为初始状态。

文档说在滑块事件中 "this" 总是指有问题的滑块,但出于某种原因它指的是 Window,我不明白为什么。

这是一个简单的实际例子https://codepen.io/gurubob/pen/MWawvQK

$(() => {
    var swipers = [];

    function initSwiper(element) {
        var swiper = new Swiper(element, {
            // Optional parameters
            direction: 'horizontal',
            loop: false,
            initialSlide: 1,
            on: {
                slideChange: () => {
                    // The docs say that "this" is always the instance of
                    // the swiper in any events, but here "this" is the
                    // window and I can't spot why????
                    // Change all other swipers back to initial slide:
                    var thisSwiper = this;
                    swipers.forEach(swiper => {
                        if(swiper != thisSwiper) swiper.slideTo(1);
                    })
                }
            }
        })

        swipers.push(swiper);
    }

    $(function(){
        $('.swiper-container').each((idx, element) => {
            initSwiper(element);
        });
    })
})

你能看出我做错了什么吗?

那是因为您在传递给 Swiper 的选项中使用箭头函数作为 slideChange 属性 的值。

箭头函数使用父作用域而不是新作用域:Arrow functions MDN

您可以只使用 swiper 变量而不是使用 this:

slideChange: () => {
                    swipers.forEach(swiperItem => {
                        if(swiper != swiperItem) swiperItem.slideTo(1);
                    })
                }

另一种选择是单独添加事件监听器:

var swiper = ...;
swiper.on('slideChange', () => ...)