0
在下面的虛擬示例代碼中,我創建了一個類(WindowResizer),它在調整窗口大小時會偵聽瀏覽器窗口,窗口重新調整大小後250毫秒計時器調用方法timerAlarm)屬於WindowResizer類。但是這個方法中的'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>
謝謝!但我不明白爲什麼它從不同的範圍調用時更改: self.windowResizeTimer = setTimeout(self.timerAlarm,250); 去: self.windowResizeTimer = setTimeout(function(){self.timerAlarm();},250); 我在哪裏可以閱讀更多關於此?或者它可能存在一個簡單的解釋? :) – Delta
您是否閱讀過標記爲dupe的問題的答案? – epascarello
是的,我做到了。現在我完全理解它。謝謝! – Delta