当前位置:网站首页>#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。
边栏推荐
- Continuous test (CT) practical experience sharing
- Rhcsa Road
- Unity making plug-ins
- Unity writes a timer tool to start timing from the whole point. The format is: 00:00:00
- OAI 5G NR+USRP B210安装搭建
- 2022 nurse (primary) examination questions and new nurse (primary) examination questions
- (work record) March 11, 2020 to March 15, 2021
- Unity load AB package
- [network planning] Chapter 3 data link layer (4) LAN, Ethernet, WLAN, VLAN
- Is it safe to open an account in flush? Which securities company is good at opening an account? Low handling charges
猜你喜欢
![[DIY]如何制作一款個性的收音機](/img/fc/a371322258131d1dc617ce18490baf.jpg)
[DIY]如何制作一款個性的收音機

Why do novices often fail to answer questions in the programming community, and even get ridiculed?

01 basic introduction - concept nouns

BeagleBoneBlack 上手记

Core principles of video games
![[weekly pit] positive integer factorization prime factor + [solution] calculate the sum of prime numbers within 100](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[weekly pit] positive integer factorization prime factor + [solution] calculate the sum of prime numbers within 100

小孩子學什麼編程?

Value of APS application in food industry

【微信小程序】运行机制和更新机制

【GET-4】
随机推荐
知识图谱构建流程步骤详解
Spark SQL chasing Wife Series (initial understanding)
[wechat applet] operation mechanism and update mechanism
Leetcode hot topic Hot 100 day 32: "minimum coverage substring"
Basic knowledge of lists
The mail command is used in combination with the pipeline command statement
[weekly pit] positive integer factorization prime factor + [solution] calculate the sum of prime numbers within 100
OLED屏幕的使用
Rhcsa Road
【每周一坑】输出三角形
Special topic of rotor position estimation of permanent magnet synchronous motor -- fundamental wave model and rotor position angle
Leetcode question 283 Move zero
Use of OLED screen
Tencent T4 architect, Android interview Foundation
2022 nurse (primary) examination questions and new nurse (primary) examination questions
Utilisation de l'écran OLED
[DSP] [Part 2] understand c6678 and create project
电子游戏的核心原理
Comment faire une radio personnalisée
Logic is a good thing