首页 > 技术文章 > nodejs EventEmitter 使用基础

sunbey 2018-02-28 14:52 原文

var events = require('events')
var util = require('util')

var Person = function(name, age){
    this.name = name,
    this.age = age
}

util.inherits(Person, events.EventEmitter)

var jack = new Person('jack', 24)
var lucy = new Person('lucy', 18)

var students = [jack, lucy]

students.forEach(function(person){
    person.on('say', function(){
        console.log(this.name + ' say: hello, I\'m ' + this.age + ' years old.' )
    })
})

jack.emit('say')
lucy.emit('say')

 

推荐阅读