变量这不会返回我的期望

时间:2015-06-01 16:57:44

标签: javascript

在下面的虚拟示例代码中,我创建了一个类(WindowResizer),它在调整大小时监听浏览器窗口,在调整窗口大小250 ms后,定时器调用属于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>

1 个答案:

答案 0 :(得分:3)

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

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

需要

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

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