25
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

EventEmitterの継承方法 (ES5,ES6)

Last updated at Posted at 2015-06-30

EventEmitterの継承方法の備忘録。ES5の場合。

ES5の場合

ES5継承(util.inherits使用)
var util = require("util");
var EventEmitter = require("events").EventEmitter;

function MyClass() {
    EventEmitter.call(this);
}

util.inherits(MyClass, EventEmitter);

MyClass.prototype.doSomething = function(data) {
    this.emit("doSomething", data);
}
ES5継承(util.inherits未使用)
var EventEmitter = require("events").EventEmitter;

function MyClass() {
    EventEmitter.call(this);
}

MyClass.prototype = Object.create(EventEmitter.prototype);

MyClass.prototype.doSomething = function(data) {
    this.emit("doSomething", data);
}

ES6の場合

ES6継承
var EventEmitter = require("events").EventEmitter;
class MyClass extends EventEmitter
{
    // 省略可
    constructor(){
        super();
    }

    doSomething(data){
        this.emit("doSomething", data);
    }
}

ES6は便利だな。。

25
27
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?