gpt4 book ai didi

javascript - 变量 this 不会返回我期望的结果

转载 作者:行者123 更新时间:2023-11-28 19:11:59 24 4
gpt4 key购买 nike

在下面的虚拟示例代码中,我创建了一个类 (WindowResizer),该类在调整大小时监听浏览器窗口,调整窗口大小后 250 毫秒,计时器调用属于 WindowResizer 类的方法 (timerAlarm) 。但此方法中的“this”变量是窗口对象。为什么?我应该怎么做才能到达 WindowResizer 的实例?

    <script>
$(document).ready(function () {
var windowResizer = new WindowResizer();
windowResizer.name = "Tester";
windowResizer.window = $(window);
windowResizer.attachEvents();
});

function WindowResizer(window) {
this.window = window;
}

WindowResizer.prototype.attachEvents = function () {
var self = this;

self.window.resize(function () {
clearTimeout(self.windowResizeTimer);
self.windowResizeTimer = setTimeout(self.timerAlarm, 250);
});
};

WindowResizer.prototype.timerAlarm = function () {
// Here the variable this is the window, but I want it to be the instance of WindowResizer that I created in the document ready-function, why!?
console.log(this);
}
</script>

最佳答案

另一个 setTimeout 函数内的 setTimeout 函数将在窗口范围内执行。您需要更改引用该方法的方式。

self.windowResizeTimer = setTimeout(self.timerAlarm, 250);

需要

self.windowResizeTimer = setTimeout(function(){self.timerAlarm();}, 250);

self.windowResizeTimer = setTimeout(self.timerAlarm.bind(self), 250);

关于javascript - 变量 this 不会返回我期望的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30579063/

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