【问题标题】:ES6 Class constructor not working in nodejs 4.4.5LTS [duplicate]ES6类构造函数在nodejs 4.4.5LTS中不起作用[重复]
【发布时间】: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 想要外部的thisdownloadthis)。必须绑定常规函数或使用更高范围的值才能到达 setTimeout 回调中的 Downloader 实例。
  • 你试过在你的构造函数中添加 super() 吗?
  • @jamesemanon 你中了靶心。添加超级正在工作。并且对应于 ES5 版本的 EventEmitter.call(this)。但是我仍然不明白为什么javascript不能为类本身建立一个this。 ES6 中没有这样的规则。
  • 在子类中,this 在调用 super() 之前不会被初始化。

标签: javascript node.js ecmascript-6


【解决方案1】:

如果从 ES6 类切换到函数不那么麻烦,那么你可以尝试:

'use strict';
const util = require('util');
const EventEmitter = require('events');

function Downloader() {
  var self = this;

  self.totalEmitted = 0;

  this.on('downloaded', function() {
    self.totalEmitted ++;
    console.log(self.totalEmitted);
  });
}

util.inherits(Downloader, EventEmitter);

Downloader.prototype.download = function(delaySecs) {
  setTimeout(() => {
      this.emit('downloaded', delaySecs);
  }, delaySecs*1000);
};

var downloader = new Downloader();
downloader.download(1);

module.exports = Downloader;

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2016-05-16
    • 2018-07-17
    • 2015-07-23
    相关资源
    最近更新 更多