在JavaScript中使用严格模式,对于胖箭头不起作用? [英] use strict in javascript not working for fat arrow?

查看:92
本文介绍了在JavaScript中使用严格模式,对于胖箭头不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个有趣的案例,其中"use strict"无法按预期在javascript中工作. 后续功能

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?

推荐答案

MDN说

与严格模式的关系

鉴于this是词法,关于this的严格模式规则将被忽略.

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规则.

The rules of lexical this take precedence over strict-mode this rules.

通过检查

定义在函数的形式参数和代码体内如何解释this引用. lexical表示this引用词法包围函数的this值. strict表示this值的使用与函数调用所提供的完全相同. global表示undefinedthis值被解释为对全局对象的引用.

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设置行为的目的而使该函数的严格/非严格状态不相关.

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.

这篇关于在JavaScript中使用严格模式,对于胖箭头不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆