这是Vue课程。计时器计时时应触发方法signOut()。计时器有效,但呼叫signOut()除外。

问题在于访问类方法。我对this,自我和访问修饰符感到困惑。
我尝试使用this.signOut(),但是它不起作用。

如何调用方法signOut

"use strict";

(async (globals, config, loader, application) => {

    const storageLocal = await loader.services.storage.local.getAsync();

    class HeaderComponent {
        #foo = a;

        constructor(tag) {
            this.tag = tag;

            this.timer();
        }

        signOut() {
            storageLocal.delete('account');
            window.location = '/signin.html';
        }

        timer() {
            //document.getElementById("timer"),
            var counter = -1;
            var timeout;
            var startTimer = function timer() {
                counter++;
                console.log(counter);

                signOut(); //<- error can't call class method
                timeout = setTimeout(timer, 10000);
            };

            function resetTimer() {
                // here you reset the timer...
                clearTimeout(timeout);
                counter = -1;
                startTimer();
                //... and also you could start again some other action
            }

            document.addEventListener("mousemove", resetTimer);
            document.addEventListener("keypress", resetTimer);
            startTimer();
        }

        data() {
            return { account: storageLocal.account };
        }
    }

    const component = new HeaderComponent('component-header')
    loader.components.set(component.tag, component);

})(window, window.config, window.loader, window.application);


请注意:

        signOut() {
            storageLocal.delete('account');
            window.location = '/signin.html';
        }

        timer() {
            //document.getElementById("timer"),
            var counter = -1;
            var timeout;
            var startTimer = function timer() {


如您所见,'signOut()'比活动函数低2级。逻辑上说它将像this.parent.signOut()一样工作,但是却没有!

EDIT3:this.signOut();将产生

Uncaught TypeError: Cannot read property 'signOut' of undefined
    at timer (header.js:30)
    at HTMLDocument.resetTimer

最佳答案

function创建一个新的上下文。您需要切换到箭头功能并使用this.signOut()。简化示例:

  timer() {
    var counter = -1;
    var timeout;
    var startTimer = () => {
      counter++;
      console.log(counter);

      this.signOut();
      timeout = setTimeout(startTimer, 1000);
    };

    setTimeout(startTimer, 1000);
  }


此外,您在一个类中定义了两个signOut()方法。

关于javascript - 在javascript类中调用类方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58877980/

10-12 04:42