簡體   English   中英

在 javascript class 中調用 class 方法

[英]Calling class methods inside javascript class

這是一個 Vue class。 當計時器滴答作響時,方法signOut()應該觸發。 計時器工作,除了調用signOut()

問題在於訪問 class 方法。 我對this 、 self 和 access 修飾符感到困惑。 我嘗試使用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創建了一個新的上下文。 您需要切換到箭頭 function 並使用this.signOut() 簡化示例:

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

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

    setTimeout(startTimer, 1000);
  }

此外,您在一個 class 中定義了兩個 signOut signOut()方法。

你需要this並像這樣調用它this.signOut()

startTimer函數不在HeaderComponent實例的上下文中運行。 startTimer中的this在作為setTimeout中的處理程序執行時將指向window

為了訪問HeaderComponent的實例,要么使用箭頭 function (如前面的回答中所指出的那樣。另見箭頭 function 表達式),它將指向外部上下文( thisHeaderComponent的實例)或定義一個標識符在指向實例的timer中(例如const self = this; )並在startTimer中使用self而不是this

將此應用於您的示例(為了保持一致性,我使用var而不是const ):

        timer() {
            var counter = -1;
            var timeout;
            var self = this;
            var startTimer = function() { // Don't use a named function here, it only leads to more confusion
                counter++;
                console.log(counter);

                self.signOut(); // Use `this` of the outer context
                timeout = setTimeout(startTimer, 10000);  // Use the declared identifier
            };

            // Rest of the method
        }

this是 Javascript 對於來自不同編程語言的人來說可能有點混亂。 如果您想了解更多細節,我建議您閱讀this參考資料閉包

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM