0

I am little new to ES6, but not with node js, but this looks little weird because when I started using arrow style function instead of function() style, I was in assumption that both are exactly same but the syntax is different. But today came to know about this case.

When I define a function like this.

exports.intent = {
  greetings: {
    matcher: ["hi", "hello"],
    reply: function(){
       console.log(this); // it prints {greetings: {..}} expected
       return this.matcher[0]; // returns "hi" which is expected.
    }
  }
}

But when I defined same function in arrow style, it throws error as this here now references the whole object instead of current object.

exports.intent = {
  greetings: {
    matcher: ["hi", "hello"],
    reply: () => {
       console.log(this); // it prints whole object {intent: {....}}
       return this.matcher[0]; // fail here.
    }
  }
}

I came to know that there are some changes in this refrencing between these 2 types of declaration. https://stackoverflow.com/a/40498293/2754029

Is there are any way so that I can refrence this to current object only?

undefined
  • 2,718
  • 9
  • 39
  • 65
  • You already learnt that they are different, so what is your question now? You asked "Is there are any way so that I can reference this to current object only?", but you already know the answer to that. Use a regular function, not an arrow function. – Paul Jan 09 '18 at 06:28
  • use this.greetings.matcher[0] – Dhananjaya Kuppu Jan 09 '18 at 06:30
  • I am looking for a way to use this and at the same time arrow style function. I do not want to use function() style, as everywhere I am using arrow style declaration. – undefined Jan 09 '18 at 06:30
  • @undefined You can't do that, arrow functions are not intended to be used everywhere. They are not just a shorthand for functions, they work differently and aren't meant to replace regular functions. When your function is meant to be a method of an object (like your case above), use a regular function. Use an arrow function when you want lexical `this`, and whichever you prefer when you're not using `this` inside the function. – Paul Jan 09 '18 at 06:31
  • No. You will not be able to override this inside an arrow function body. – Sreenivas Shenoy Jan 09 '18 at 06:31
  • Arrow functions cannot be used to write object methods because, as you have found, since arrow functions assume the this of the lexically enclosing function context, the this within an object definition is either the window or something else. – Suresh Ponnukalai Jan 09 '18 at 06:31

1 Answers1

3

No. You will not be able to override this inside an arrow function body. Even if you try to bind it, it doesn't work. This one is an interesting article I came across recently.

Osama Rizwan
  • 601
  • 1
  • 4
  • 18