I found an interesting case where "use strict" is not working as expected in javascript. Following functions
"use strict";
var y = () => {
console.log(this);
}
var x = function () {
console.log(this);
}
x(); // undefined due to use strict
y(); // window object
I think fat arrow context should also be overwritten by undefined, or is my assumption wrong?
Arrow functions allow us to use the fat arrow => operator to quickly define JavaScript functions, with or without parameters. We are able to omit the curly braces and the function and return keywords when creating a new JavaScript function to write shorter function syntax.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
Strict mode is declared by adding "use strict"; to the beginning of a script or a function.
Arrow functions don't have the arguments object. Therefore, if you have a function that uses arguments object, you cannot use the arrow function.
MDN says of arrow functions:
Relation with strict mode
Given that
this
is lexical, strict mode rules with regard tothis
are just ignored.var f = () => {'use strict'; return this}; f() === window; // or the global object
The rules of lexical this
take precedence over strict-mode this
rules.
We can see this easily in the ES2015 specification by examining the plain-English description of possible values for a function's [[ThisMode]]
slot, which can be lexical
, strict
, or global
:
Defines how
this
references are interpreted within the formal parameters and code body of the function.lexical
means thatthis
refers to thethis
value of a lexically enclosing function.strict
means that thethis
value is used exactly as provided by an invocation of the function.global
means that athis
value ofundefined
is interpreted as a reference to the global object.
In other words, a function's this
behavior can either be strict, non-strict, or lexical. If a function's [[ThisMode]]
is lexical (as it is for an arrow function), it renders the function's strict/non-strict status irrelevant for the purpose of determining this
-setting behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With