{ console.log(t-6ren">
gpt4 book ai didi

javascript - 在 javascript 中使用严格不适用于粗箭头?

转载 作者:数据小太阳 更新时间:2023-10-29 04:36:18 26 4
gpt4 key购买 nike

我发现了一个有趣的案例,其中“use strict”在 javascript 中没有按预期工作。后续功能

"use strict";

var y = () => {
console.log(this);
}

var x = function () {
console.log(this);
}

x(); // undefined due to use strict
y(); // window object

我觉得 fat arrow context 也应该被 undefined 覆盖,或者我的假设是错误的?

最佳答案

MDN 说 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

词法 this 规则优先于严格模式 this 规则。

通过检查 a function's [[ThisMode]] slot 的可能值的简单英语描述,我们可以在 ES2015 规范中轻松地看到这一点。 ,可以是lexicalstrictglobal:

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.

换句话说,函数的this 行为可以是严格的、非严格的或词法的。如果函数的 [[ThisMode]] 是词法的(就像箭头函数一样),它会使函数的严格/非严格状态与确定 this 的目的无关>-设置行为。

关于javascript - 在 javascript 中使用严格不适用于粗箭头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com