javascript - 更改并尝试进行一些调整时,元素数组在类中变得未定义
问题描述
我构建一个对象并按类名收集所有元素,然后在更改时我想对它们做一些工作。当我构造它的对象时,它可以工作,但是在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() {
的时候,因为函数看不到父变量,但我不确定如何在调整大小时直接调用函数。
解决方案
您可以在跳转到函数之前存储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>
推荐阅读
- c# - 如何防止 C# WPF 中的 UI 挂起?
- sql - 在 select join 语句上添加自动递增列
- c# - 您可以直接使用“CALL Proc_name()”作为字符串,或者在 C# 中使用 CommandType.StoredProcedure
- c# - 为什么 SetSystemTime() 在下午的行为不同?
- jhipster - Using multiple field for combo & list
- node.js - 如何在 Node js Swagger.json 中传递查询参数?
- spring-boot - Spring webflux - 多单声道
- plsql - Oracle UTL_FILE.fremove(或frename)权限被拒绝
- css - Sass - 从指定了多个值的属性中获取一个值
- c - 映射文件在读取时不占用内存,但在写入时占用