所以我有这门课。它应该创建一个超时,让我看看它做了多远。但是,它什么也没有返回。有谁知道什么是错的?这会在浏览器中返回错误。它只适用于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();
}
// ...
通过这种方式,"getting time left"
沿着this.start
时间记录。
所以你为字段timeLeft
编写了getter,但是你将你的字段命名为start
。你也可以只扩展类,但你试图扩展不正确的功能。
不同的浏览器行为不同,Node.js是另一个运行JS的环境。这就是为什么我们使用转换过程来统一不同环境中的JS行为。