每隔500毫秒输出一个点,输出3次。
全部代码如下,使用事件机制。
var util=require('util'); var events=require('events'); function Pulsar(speed, times) { events.EventEmitter.call(this); this.speed=speed; this.times=times; // 设置监听器 this.on('pulse',()=>{ console.log('.'); }); } // 继承 util.inherits( Pulsar, events.EventEmitter ); // 写一个start方法 Pulsar.prototype.start=function() { var self = this; var id=setInterval( function() { self.emit('pulse'); self.times--; if (self.times==0) { clearInterval(id); } }, this.speed); }; // 执行。 var pulsar= new Pulsar(500,3); pulsar.start();
该程序执行结果如下:
.
.
.
然后就结束了。
仔细观察,发现代码中的定时器部分的this引用有点丑陋,于是有两种解决方案,
1、使用bind绑定this,bind是所有函数的一个自带的内部方法。
被改动的代码如下:
// 写一个start方法 Pulsar.prototype.start=function() { var id=setInterval( function() { this.emit('pulse'); this.times--; if (this.times==0) { clearInterval(id); } }.bind(this), this.speed); };
把匿名函数用括号括起(不用括号也可以),然后加bind方法绑定自身,感觉应该还不错,可以执行,但是还有更好的方案。
2、使用箭头函数。
// 写一个start方法 Pulsar.prototype.start=function() { var id=setInterval( ()=> { this.emit('pulse'); this.times--; if (this.times==0) { clearInterval(id); } }, this.speed); };
node果然趣味无穷,花样比较多。