use strict in javascript not working for fat arrow?

江枫思渺然 提交于 2020-07-08 06:12:06

问题


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?


回答1:


MDN says of arrow functions:

Relation with strict mode

Given that this is lexical, strict mode rules with regard to this 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 that this refers to the this value of a lexically enclosing function. strict means that the this value is used exactly as provided by an invocation of the function. global means that a this value of undefined 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.



来源:https://stackoverflow.com/questions/36427862/use-strict-in-javascript-not-working-for-fat-arrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!