在 javascript 中使用严格不适用于粗箭头?
use strict in javascript not working for fat arrow?
我发现了一个有趣的案例,其中 "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
规则。
我们可以在 ES2015 规范中通过检查 a function's [[ThisMode]]
slot 可能值的简单英语描述轻松地看到这一点,这些值可以是 lexical
、strict
或 [=18] =]:
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]]
是词法的(就像箭头函数一样),它会使函数的 strict/non-strict 状态与确定 this
设置行为无关。
我发现了一个有趣的案例,其中 "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 tothis
are just ignored.var f = () => {'use strict'; return this}; f() === window; // or the global object
词法 this
规则优先于严格模式 this
规则。
我们可以在 ES2015 规范中通过检查 a function's [[ThisMode]]
slot 可能值的简单英语描述轻松地看到这一点,这些值可以是 lexical
、strict
或 [=18] =]:
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.
换句话说,函数的 this
行为可以是严格的、非严格的或词法的。如果函数的 [[ThisMode]]
是词法的(就像箭头函数一样),它会使函数的 strict/non-strict 状态与确定 this
设置行为无关。