对象中的 JS 函数消失

JS functions in object disappears

本文关键字:函数 消失 JS 对象      更新时间:2023-09-26

当我最初调用这个函数时:

var session = function(){
    console.error(service.get());
    if(service.get().session === undefined){
        $localStorage.user.session = {
            timeLeft: 0,  //  Time left until a user session ends (in minutes).
            start: function(timeLeft) {
                $localStorage.user.session.timeLeft = timeLeft;
                $localStorage.user.session.interval;
            },
            stop: function(){
                $interval.cancel($localStorage.user.session.interval);
            },
            interval: $interval(function () {
                $localStorage.user.session.timeLeft -= 1;
                if($localStorage.user.session.timeLeft <= 0){
                    $state.go('signin');
                }
            }, 0.125 * 60000)
        };
    }
    return $localStorage.user.session;
};

function sessionRestart(){
    session();
};
sessionRestart();

它创建session对象及其所有变量,但是当我重新加载页面时,它不会填充作为函数的变量。我该如何解决这个问题?


编辑该应用程序AngularJS,我正在使用ngStorage进行$localStorage,并且代码用于用户会话,可以在我的应用程序的factory中找到。

MarcosPérezGude让我想到了解决问题的方法。哪些是将$interval移到解决了我问题的$localStorage之外。不知道为什么它不起作用。

代码现在如下所示:

var session,
    startSession: function(timeLeft) {
        if($localStorage.user.session === undefined){
            if(timeLeft === undefined){
                timeLeft = 0;
            }
            $localStorage.user.session = {
                timeLeft: timeLeft
            };
        }
        if (session === undefined) {
            session = $interval(function () {
                $localStorage.user.session.timeLeft -= 1;
                if($localStorage.user.session.timeLeft === undefined){
                    service.stopSession();
                }
                if($localStorage.user.session.timeLeft <= 0){
                    $state.go('signin');
                }
            }, 1 * 60000);  //  Time in milliseconds. Minutes * milliseconds = total milliseconds before the interval repeats.
        }
    },
    stopSession: function() {
        $interval.cancel(session);
        session = undefined;
    };