0
var emitter = require('events').EventEmitter;
var util = require('util');

let Person = function (name) {
    this.name = name;

};

util.inherits(Person, emitter);
let p = new Person("jonny");

p.on('speak', (said) => {
    console.log(` ${this.name} said: ${said}`);

});

p.emit('speak', "You may delay but time will not!");

console will return

undefined said: You may delay but time will not!

if you change from lambda back

p.on('speak', function(said) {
    console.log(` ${this.name} said: ${said}`);

});

it works. can some explain to me why this acts differently with syntactic sugar changes?

Mickey Perlstein
  • 2,508
  • 2
  • 30
  • 37

1 Answers1

0

Arrow function (Lambda) has not neither this nor arguments. And if you find this or arguments , it belongs to its function caller .

Therefore , you need to use classic function until upgrading events package & supporting this feature .

Update:

IF you love arrow function & you insist to use it , i suggest to override on method AND convert arrow function to classic-function using eval

class Person extends require('events').EventEmitter{

     constructor(name){
      super();
       this.name=name;
     }
     on(event,arrow){
         super.on.call(this,event,eval(`(function${arrow.toString().replace('=>','')})`));
     }
}

let p = new Person("jonny");

p.on('speak', (said) => {
    console.log(` ${this.name} said: ${said}`);

});

p.emit('speak', "You may delay but time will not!");

DEMO :

enter image description here

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • Please don't recommend `eval`, that's not at all a general answer. If that function depended on anything besides `this` and `said`, it would break immediately. – loganfsmyth Aug 01 '16 at 23:10
  • i knew,,, hust for his requirements – Abdennour TOUMI Aug 01 '16 at 23:22
  • 1
    @AbdennourTOUMI thanks for your answer, but I did not require anything. I asked why javascript is behaving in a way that I do not understand. I come from C#, where "arrow functions" do not act in this manner and are in fact syntactic sugar. – Mickey Perlstein Aug 04 '16 at 12:45