Javascript作用域错误问题

Javascript scope error issue

本文关键字:问题 错误 作用域 Javascript      更新时间:2023-09-26

我编写了这段启动计时器的代码。我触发一个函数,当它达到0时重新启动计时器。它工作,但我得到一个错误在控制台中说Uncaught TypeError:不能读取属性'restartTimer'的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;
};

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

尝试改变你的surveyTimer的实现,它目前在哪里:

counterEnd();

:

counterEnd.call(options);