用于超时类的getter返回undefined

问题描述 投票:-1回答:3

所以我有这门课。它应该创建一个超时,让我看看它做了多远。但是,它什么也没有返回。有谁知道什么是错的?这会在浏览器中返回错误。它只适用于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)
javascript node.js
3个回答
2
投票

我没有看到任何理由从setTimeout扩展。 setTimeout不是类或构造函数。节点显然让你逃脱它,但浏览器没有。相反,这个怎么样:

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

0
投票

看起来get方法定义不起作用,因为setTimeout定义不允许它。我认为你会更好地使用构图而不是扩展:

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

通过这种方式,"getting time left"沿着this.start时间记录。


0
投票

所以你为字段timeLeft编写了getter,但是你将你的字段命名为start。你也可以只扩展类,但你试图扩展不正确的功能。

不同的浏览器行为不同,Node.js是另一个运行JS的环境。这就是为什么我们使用转换过程来统一不同环境中的JS行为。

© www.soinside.com 2019 - 2024. All rights reserved.