`
xieye
  • 浏览: 803898 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

node中的this学习体会(有代码示例)

阅读更多
做一个定时器功能,用node的对象和事件机制。
每隔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果然趣味无穷,花样比较多。




1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics