1 通过测试,箭头函数中的this,指箭头函数位置上所在类的对象。
this.name = 'haha';
class Channel extends events.EventEmitter{
constructor(){
super();
this.clients = {};
this.subscriptions = {};
this.name='didi';
}
}
const channel = new Channel();
channel.on('join',(id,client) => {
console.log('this.name=',this.name);//haha
})
net.createServer( client => {
const id = `${client.remoteAddress}:${client.remotePort}`;
channel.emit('join', id, client);
client.on('data',data => {
const msg = data.toString();
channel.emit('broadcast',id,msg);
})
}).listen(8888);
2 普通函数中的this,指调用者对象。
const events = require('events');
const net = require('net');
this.name = 'haha';
class Channel extends events.EventEmitter{
constructor(){
super();
this.clients = {};
this.subscriptions = {};
this.name='didi';
}
}
const channel = new Channel();
console.log("object clients=",channel.clients);
channel.on('join',function(id,client) {
console.log('this.name=',this.name);//didi
})
net.createServer( client => {
const id = `${client.remoteAddress}:${client.remotePort}`;
channel.emit('join', id, client);
client.on('data',data => {
const msg = data.toString();
channel.emit('broadcast',id,msg);
})
}).listen(8888);