首页 > 解决方案 > 更改并尝试进行一些调整时,元素数组在类中变得未定义

问题描述

我构建一个对象并按类名收集所有元素,然后在更改时我想对它们做一些工作。当我构造它的对象时,它可以工作,但是在WidthChecker()宽度上做一些工作时会改变 become undefined

class SlickController {
    constructor () {
        this.$mobileSlicksCarousels;
    }
    Init() {
        this.$mobileSlicksCarousels = document.getElementsByClassName("slick_carousels_mobile-only"); // view in console says this is valid, I see the objects
        this.WidthChecker();
    }
    WidthChecker() {
        var width = $(window).width();
        $(window).on('resize', function() {
            console.log(this.$mobileSlicksCarousels); // they become undefined in here, lost and none of the content afterwords be seen
            if ($(this).width() !== width) {
                width = $(this).width();
                if (width < 491) {
                    this.$mobileSlicksCarousels.forEach( carousel => {
                        this.SlickMobile(carousel);
                    });
                } else if (width > 490) {
                    this.$mobileSlicksCarousels.forEach( carousel => {
                        this.UnSlickMobile(carousel);
                    });
                }
            }
        });
    }

    SlickMobile (toSlick) {
        console.log(toSlick);
        toSlick.slick();
    }

    UnSlickMobile (unSlick) {
        unSlick.slick('unslick');
    }
}


// call and start width checker
slick_Controller.Init();

我认为问题出在我调用$(window).on('resize', function() {的时候,因为函数看不到父变量,但我不确定如何在调整大小时直接调用函数。

标签: javascript

解决方案


您可以在跳转到函数之前存储this在变量中,或者您可以绑定函数但随后您会丢失 jquery 上下文并且无法使用$(this)表达式。

看看例子

class Test {
    constructor () {
        this.property = 1;
    }

    Func() {
        var width = $(window).width();
        const that = this;
        $(window).on('load', function() {
            console.log(that.property);
            console.log($(this).width());
        });
    }
    
    Func1() {
        var width = $(window).width();
        $(window).on('load', (function() {
            console.log(this.property);
            console.log($(window).width());
        }).bind(this));
    }
    
    Func2() {
        var width = $(window).width();
        $(window).on('load', this.OnResize.bind(this));
    }
    
    OnResize(event) {
      console.log(this.property);
      console.log($(event.target).width());
    }

}

const test = new Test();
test.Func();
test.Func1();
test.Func2();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读