当前位置:网站首页>#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。
边栏推荐
- 8086 instruction code summary (table)
- Tencent byte and other big companies interview real questions summary, Netease architects in-depth explanation of Android Development
- PHP online examination system version 4.0 source code computer + mobile terminal
- 2022 Guangdong Provincial Safety Officer C certificate third batch (full-time safety production management personnel) simulation examination and Guangdong Provincial Safety Officer C certificate third
- Recyclerview GridLayout bisects the middle blank area
- 【每周一坑】计算100以内质数之和 +【解答】输出三角形
- [diy] how to make a personalized radio
- [DIY]如何制作一款个性的收音机
- 逻辑是个好东西
- Boder radius has four values, and boder radius exceeds four values
猜你喜欢
What programming do children learn?
B-杰哥的树(状压树形dp)
use. Net drives the OLED display of Jetson nano
[weekly pit] output triangle
[network planning] Chapter 3 data link layer (3) channel division medium access control
02 基础入门-数据包拓展
SSO single sign on
Enumeration gets values based on parameters
强化学习-学习笔记5 | AlphaGo
Digital triangle model acwing 1018 Minimum toll
随机推荐
Statistical inference: maximum likelihood estimation, Bayesian estimation and variance deviation decomposition
强化学习-学习笔记5 | AlphaGo
【每周一坑】正整数分解质因数 +【解答】计算100以内质数之和
Detailed introduction of distributed pressure measurement system VIII: basic introduction of akka actor model
JMeter server resource indicator monitoring (CPU, memory, etc.)
Rhcsa Road
Force deduction brush question - 98 Validate binary search tree
[weekly pit] output triangle
B-杰哥的树(状压树形dp)
永磁同步电机转子位置估算专题 —— 基波模型类位置估算概要
Digital triangle model acwing 1018 Minimum toll
报错分析~csdn反弹shell报错
Continuous test (CT) practical experience sharing
小孩子学什么编程?
Le lancement du jupyter ne répond pas après l'installation d'Anaconda
Unity writes a timer tool to start timing from the whole point. The format is: 00:00:00
Quel genre de programmation les enfants apprennent - ils?
Solution to the 38th weekly match of acwing
Function optimization and arrow function of ES6
Initial experience of addresssanitizer Technology