【问题标题】:Javascript scope error issueJavascript范围错误问题
【发布时间】:2015-05-19 19:37:26
【问题描述】:

我编写了这段代码来启动一个计时器。我触发了一个函数,该函数在计时器达到 0 时重新启动它。它可以工作,但我在控制台中收到一个错误,显示 Uncaught TypeError: Cannot read property 'restartTimer' of undefined。跟this.restartTimer()有关;

timer = utility.math.surveyTimer({
    seconds: time,
    onUpdateStatus: function(remainingTime) {
        $(surveyTimerNode).text(remainingTime);
    },
    restartTimer: function() {
        window.TimerInterval = timer.start();
    },
    onCounterEnd: function() {
        if (utility.bool.isQuestionScreen()) {
            if (utility.bool.surveyWillLoop()) {
                data.setPersistentSurveyData('DSM_SURVEY_SCREENS', surveyScreens);
                data.setPersistentSurveyData('DSM_SURVEY_SCREEN_ORDER', surveyScreenOrder);
                
                tagData = data.getPersistentSurveyData('DSM_SURVEY_DATA');
                apiParam = api.helper.buildAPIParam('surveyTimeout', tagData);
                api.post.postToAPI(apiParam);
                
                parent.resetSurveyProgress();
                parent.moveToNextScreen();
                this.restartTimer();
            } else {
                parent.goToEndscreen();
            }
        }
    }
});
window.TimerInterval = timer.start();

JSLint 中没有错误,只是运行时出错。奇怪的是它起作用了,计时器确实重置了。如何消除此错误? 下面是实际执行计时器计数的函数:

this.surveyTimer = function (options) {
    var timer,
        instance = this,
        minutes,
        secondsMinusMinutes,
        remainingTime,
        seconds = options.seconds || 30,
        updateStatus = options.onUpdateStatus || function () {
            return undefined;
        },
        counterEnd = options.onCounterEnd || function () {
            return undefined;
        };

    function zeroPad(n) {
        return (n < 10) ? ("0" + n) : n;
    }

    function decrementCounter() {
        minutes = Math.floor(seconds / 60);
        secondsMinusMinutes = seconds - minutes * 60;
        remainingTime = minutes + ':' + zeroPad(secondsMinusMinutes);

        updateStatus(remainingTime);
        if (seconds === 0) {
            counterEnd();
            instance.stop();
        }
        seconds -= 1;
    }

    this.start = function () {
        clearInterval(timer);
        timer = 0;
        seconds = options.seconds;
        timer = setInterval(decrementCounter, 1000);
        return timer;
    };

    this.stop = function () {
        clearInterval(timer);
    };
    return this;
};

【问题讨论】:

    标签: javascript timer scope closures object-literal


    【解决方案1】:

    只是猜测,但我认为您在选项对象中使用 this 不是您认为的 this...

    尝试更改您当前的surveyTimer 实现:

    counterEnd();
    

    到:

    counterEnd.call(options);
    

    【讨论】:

    • 感谢史蒂夫的输入,但这样做会阻止计时器重新启动。
    • 当我添加你的代码时,没有。错误消失。但我认为那是因为没有调用该方法。
    猜你喜欢
    • 2018-07-06
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多