Pavan Gangireddy
Pavan Gangireddy

Reputation: 427

How to determine the correct `this` inside a regular arrow fn with "strict" and "non-strict" mode?

For the below code snippet

Case 1: Strict mode

"use strict"

let obj = {
  method: function(){
    console.log(this);
  },
  arrowMethod: () => {
    console.log(this);
  }
};

obj.method(); // call 1
obj.arrowMethod(); // call 2

let method = obj.method;
let arrowMethod = obj.arrowMethod;

method(); // call 3
arrowMethod(); // call 4

The output is:

{method: ƒ, arrowMethod: ƒ}
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
undefined
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}

Case 2: Non-Strict mode

Same snippet will output

{method: ƒ, arrowMethod: ƒ}
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}

My understanding is that:

In the strict mode,

In the non-strict mode,

Question

Upvotes: 2

Views: 84

Answers (1)

Bergi
Bergi

Reputation: 664936

Yes, the rule for strict mode functions not defaulting from undefined to the global object doesn't apply to arrow functions, since they don't have their own this at all. It always is the this value from the outer scope. And that's window in your example.

What might matter is whether the function they are defined in uses strict mode or not, as that's where the arrow function gets its value from:

 function strictMake() {
     "use strict";
     return () => { console.log(this == window); };
 }
 function sloppyMake() {
     return () => { console.log(this == window); };
 }

 const arrowFromStrict = strictMake();
 const arrowFromSloppy = sloppyMake();

 arrowFromStrict();
 arrowFromSloppy();

Upvotes: 2

Related Questions