Wednesday 7 June 2017

node.js arrow function this

I'm new to node.js so please bear with me.

I have a simple class definition like this:

var Player = function(name){
    this.name=name;
}

and I made the object inherit eventsEmitter like this (of courser i have required "events" and "util" in the beginning):

util.inherits(Player,events.EventEmitter);

and i built a couple of objects from it like this:

var p1 = new Player('p1');
var p2 = new Player('p2');

now, heres the problem: When i code the emit function with regular function, everything is fine:

p1.on('say',function(msg) { console.log(this.name)});
p1.emit('say', 'hey buddy!')

but when i use fat arrow function i get undefined:

p1.on('say', (msg) => console.log(this.name));
p1.emit('say', 'hey buddy!')

I have heard about this in fat arrow but i cant recall :(



via Amir Shahbabaie

No comments:

Post a Comment