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,
call 1
- When a function is called as a method of an object, this is set to the object the method is called on.call 2
- No matter what, arrowMethod's this is set to what it was when it was created (in the example above, the global object).call 3
- If the value of this is not set when entering an execution context, it remains undefined.call 4
No matter what, arrowMethod's this is set to what it was when it was created (in the example above, the global object).
In the non-strict mode,
call 1
- When a function is called as a method of an object, this is set to the object the method is called on.call 2
- No matter what, arrowMethod's this is set to what it was when it was created (in the example above, the global object).call 3
- Since the code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is a window in a browser.call 4
- No matter what, arrowMethod's this is set to what it was when it was created (in the example above, the global object).
Question
Isn't like for
call 4
inCase 1: Strict mode
, as the value of this is not set when an arrow fn is created, it remains undefined all the time?or
Is it like strict mode doesn't apply to arrow fns, hence at the time of creation of arrow fn, this is set to window object?