簡體   English   中英

超時類的Getter返回未定義

[英]Getter for timeout class returns undefined

所以我有這節課。 它應該創建一個超時,使我可以查看完成的時間。 但是,它什么也不返回。 有人知道怎么了嗎? 這將在瀏覽器中返回錯誤。 它僅適用於node.js

class Timeout extends setTimeout{
    constructor(){
        super(...arguments)
        this.start = new Date()
    }
    get timeLeft(){
        console.log('getting time left')
        return this.start
    }
}
console.log(new Timeout().timeLeft)

我看不出有任何理由要從setTimeout擴展。 setTimeout不是類或構造函數。 Node顯然可以讓您擺脫它,但是瀏覽器卻不能。 取而代之的是:

 class Timeout { constructor(...args) { setTimeout(...args); this.start = new Date(); } get timeLeft(){ console.log('getting time left'); return this.start; } } new Timeout(() => console.log('timer went off'), 1000).timeLeft 

似乎get方法定義不起作用,因為setTimeout定義不允許它。 我認為您最好使用合成而不是擴展:

class Timeout {
  constructor() {
    this.timeout = new setTimeout(...arguments);
    this.start = new Date();
  }
  // ...

這樣, "getting time left"將記錄在this.start時間中。

因此,您已經為名為timeLeft字段編寫了getter方法,但是將字段命名為start 另外,您只能擴展類,但是您嘗試擴展不正確的函數。

不同的瀏覽器的行為不同,Node.js是另一個運行JS的環境。 這就是為什么我們使用翻譯過程來統一跨不同環境的JS行為的原因。

暫無
暫無

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

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