0

In the dummy example code below, I have created a class (WindowResizer) that listens to the browser window when it get resized, 250 ms after the window is resized a timer calls a method (timerAlarm) that belongs to the WindowResizer class. But the 'this' variable in this method is the window object. Why? And what should I do to reach the instance of my 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>
Delta
  • 171
  • 11

1 Answers1

3

The setTimeout function inside the other setTimeout function is going to execute in the window scope. You need to change how you reference the method.

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

needs to be

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

or

self.windowResizeTimer = setTimeout(self.timerAlarm.bind(self), 250);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thank you! But I can't understand why it is called from different scopes when changing from: self.windowResizeTimer = setTimeout(self.timerAlarm, 250); to: self.windowResizeTimer = setTimeout(function(){self.timerAlarm();}, 250); Where can I read more about this? Or maybe it exists a simple explanation? :) – Delta Jun 01 '15 at 17:07
  • Did you read the answer to the question that was marked as dupe? – epascarello Jun 01 '15 at 17:37
  • Yes, I did. Now I perfectly understand it. Thank you! – Delta Jun 01 '15 at 19:27