0

I want to clarify the 'this' within a promise then() or catch() function scope. Ex:

//this= 1     
this.promiseFunction("id1").then(
                (response) => {
                     //this = 2 
                     //what is 'this' here ?
                }).catch(() => {
                     //this = 3
                     //what is 'this' here ?
                });

Is 'this' referred by 1 and 2 are equal? How does that happen?

Samitha Chathuranga
  • 1,536
  • 4
  • 25
  • 56
  • 2
    yes - because arrow functions work like that - take on the `this` of the enclosing scope (I think that's how it's worded) - from the docs *An arrow function does not create its own this context, so this has its original meaning from the enclosing context.* – Jaromanda X Jun 29 '17 at 05:13
  • @JaromandaX—which "docs"? – RobG Jun 29 '17 at 05:16
  • In this specific case, you need to learn about arrow functions. In general, promise methods (`then`, `catch`) don't set any `this` context when they invoke the callback, so it'll be `undefined` in a normal `function` (and the global object in a sloppy mode one). – Bergi Jun 29 '17 at 05:18
  • From EMCA-262: "*An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.*" In other words, an arrow function uses the *this* of its enclosing execution context. – RobG Jun 29 '17 at 05:20
  • this.promiseFunction("id1").then(function myFunction(ddd) { //this = 3 // this here ? } ) This is not an arrow function now. So 'this' here(3) should be different to this(1) ? – Samitha Chathuranga Jun 29 '17 at 05:33

0 Answers0