Closed cycold closed 6 years ago
/**
* Created by cycold on 17/02/2017.
*/
let EventEmitter = require("events")
// EventEmitter是一个函数
/**
* 比如EventEmitter有如下的定义
*
* function EventEmitter() {
* this._events = []
* this._maxListeners = this._maxListeners || undefined;
* }
*
* EventEmitter.prototype.on = function(){
* console.log(this._events)
* }
*
* EventEmitter.prototype.emit = function(){
* console.log(this._events)
* }
*/
// 定义一个构造函数(类), 需要继承EventEmitter类
function Person(name = "eric") {
// 注意这里一定要这么调用一下, 是为了继承EventEmitter实例对象本身的属性, 这些属性不在EventEmitter.prototype对象中
EventEmitter.call(this) // call super constructor. 相当于别的语言的调用父类的构造函数一样
this.name = name
}
// 肯定需要继承原型了
Person.prototype = Object.create(EventEmitter.prototype)
// 更新constructor 因为之前的constroctor还是EventEmitter,显然不正确
Person.prototype.constructor = Person
let p = new Person()
p.on('name', function () {
console.log("\nname: %s", this.name) // 这里的this执行 p
})
setTimeout(() => { p.emit("name") }, 2000)