当前位置:网站首页>#yyds干货盘点#重新梳理箭头函数的this
#yyds干货盘点#重新梳理箭头函数的this
2022-07-06 12:39:00 【51CTO】
记得之前分享过this的用法,是关于普通函数、构造函数的this,今天主要分享ES6箭头函数的this。先看普通函数下的this。
普通函数下的this:
- 在普通函数中的this总是代表它的直接调用者,在默认情况下,this指的是window,
- 在严格模式下,没有直接调用者的函数中的this是 undefined使用
- call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象
箭头函数中的this:
- 箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),
- 而不是执行时的对象, 定义它的时候,可能环境是window,也有可能是其他的。
普通函数
test是一个全局函数,也就是挂载在window对象下的 test()等价于window.test();
func的宿主环境是obj,所以func里面的this是obj。 定时器中的函数,由于没有默认的宿主对象,所以this指向window 严格模式下的this:
严格模式
在严格模式下,没有直接调用者的函数中的this是 undefined
有直接调用者的this是它的调用者
箭头函数
此时的 this继承自obj, 指的是定义它的对象obj, 而不是 window
因为f1定义时所处的函数 中的 this是指的 obj, setTimeout中的箭头函数this继承自f1,所以不管有多层嵌套,都是 obj
箭头函数没有this的绑定,必须通过查找作用链来决定其值。如果箭头函数被非箭头函数包含,则this绑定的是最近以层的非箭头函数的this;否则。this的值会被设置为undefined。 箭头函数在定义的时候它所处的环境相当于是window, 所以在箭头函数内部的this函数window。
边栏推荐
- 2022 nurse (primary) examination questions and new nurse (primary) examination questions
- Quel genre de programmation les enfants apprennent - ils?
- Tencent byte Alibaba Xiaomi jd.com offer got a soft hand, and the teacher said it was great
- 【每周一坑】信息加密 +【解答】正整数分解质因数
- (工作记录)2020年3月11日至2021年3月15日
- Web security - payload
- 01 basic introduction - concept nouns
- 7. Data permission annotation
- 自定义限流注解
- Detailed explanation of knowledge map construction process steps
猜你喜欢
【每周一坑】信息加密 +【解答】正整数分解质因数
APS taps home appliance industry into new growth points
use. Net analysis Net talent challenge participation
【每周一坑】正整数分解质因数 +【解答】计算100以内质数之和
报错分析~csdn反弹shell报错
知识图谱之实体对齐二
I've seen many tutorials, but I still can't write a program well. How can I break it?
Use of OLED screen
Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache
Enumeration gets values based on parameters
随机推荐
Detailed explanation of knowledge map construction process steps
22-07-05 upload of qiniu cloud storage pictures and user avatars
In line elements are transformed into block level elements, and display transformation and implicit transformation
7、数据权限注解
Build your own application based on Google's open source tensorflow object detection API video object recognition system (IV)
BUUCTF---Reverse---easyre
Rhcsa Road
Unity making plug-ins
[weekly pit] output triangle
SQL injection 2
01 basic introduction - concept nouns
JVM_ Common [interview questions]
Common doubts about the introduction of APS by enterprises
[DSP] [Part 1] start DSP learning
Enumeration gets values based on parameters
电子游戏的核心原理
【DSP】【第一篇】开始DSP学习
JMeter server resource indicator monitoring (CPU, memory, etc.)
【GET-4】
Variable star --- article module (1)