【发布时间】:2016-06-11 21:46:36
【问题描述】:
我正在尝试编写一个假的下载器,它基本上会休眠一段时间并发出“下载”事件。我还想要我自己的变量来跟踪发出的事件数量。 这段代码抛出如下错误:
ReferenceError: this is not defined
代码:
'use strict';
const EventEmitter = require('events');
class Downloader extends EventEmitter{
constructor(){
this.totalEmitted = 0;
}
download(delaySecs){
setTimeout(() => {
this.emit('downloaded',delaySecs);
this.totalEmitted ++;
},delaySecs*1000)
}
}
module.exports = Downloader;
如果我评论 this.totalEmitted,它可以正常工作。
更新:
当我完全消除构造函数时,它开始正常工作。
甚至使用空的构造函数也会导致 this 引用错误。
我不确定节点 4.4.5 是否支持构造函数。
解决方法:
'use strict';
const EventEmitter = require('events');
class Downloader extends EventEmitter{
download(delaySecs){
setTimeout(() => {
if(this.totalEmitted == undefined) this.totalEmitted = 0;
this.totalEmitted ++;
this.emit('downloaded',delaySecs,this.totalEmitted);
},delaySecs*1000)
}
}
module.exports = Downloader;
【问题讨论】:
-
如果你需要
this,不要使用箭头函数。尝试改写成常规函数 -
@vicodin,实际上在这种情况下不使用箭头函数会导致问题。 user3151330 想要外部的
this(download的this)。必须绑定常规函数或使用更高范围的值才能到达setTimeout回调中的Downloader实例。 -
你试过在你的构造函数中添加 super() 吗?
-
@jamesemanon 你中了靶心。添加超级正在工作。并且对应于 ES5 版本的 EventEmitter.call(this)。但是我仍然不明白为什么javascript不能为类本身建立一个this。 ES6 中没有这样的规则。
-
在子类中,
this在调用super()之前不会被初始化。
标签: javascript node.js ecmascript-6