超时类的Getter返回未定义的值



所以我有这个类。它应该创建一个超时,让我看到它完成了多远。然而,它什么也不回。有人知道怎么了吗?这会在浏览器中返回一个错误。它只适用于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不是类或构造函数。节点显然可以让你逃脱惩罚,但浏览器不能。相反,这个怎么样:

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();
}
// ...

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

所以您为名为timeLeft的字段编写了getter,但将字段命名为start。此外,您只能扩展类,但您试图扩展的函数是不正确的。

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

最新更新