当前位置:网站首页>#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。
边栏推荐
- 【每周一坑】计算100以内质数之和 +【解答】输出三角形
- 【每周一坑】信息加密 +【解答】正整数分解质因数
- Learn to punch in Web
- Web security - payload
- Continuous test (CT) practical experience sharing
- PHP online examination system version 4.0 source code computer + mobile terminal
- (work record) March 11, 2020 to March 15, 2021
- Spark SQL chasing Wife Series (initial understanding)
- 2110 summary of knowledge points and common problems in redis class
- Detailed introduction of distributed pressure measurement system VIII: basic introduction of akka actor model
猜你喜欢

Number of schemes from the upper left corner to the lower right corner of the chessboard (2)

B-jiege's tree (pressed tree DP)

RT thread I2C tutorial

【DSP】【第一篇】开始DSP学习

Spark SQL chasing Wife Series (initial understanding)

Rhcsa Road

01 basic introduction - concept nouns

【DSP】【第二篇】了解C6678和创建工程

BUUCTF---Reverse---easyre

Learn to punch in Web
随机推荐
逻辑是个好东西
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
Application layer of tcp/ip protocol cluster
Pytest (3) - Test naming rules
Summary of different configurations of PHP Xdebug 3 and xdebug2
C language games - three chess
Logic is a good thing
Deep learning classification network -- zfnet
【每周一坑】信息加密 +【解答】正整数分解质因数
Zoom with unity mouse wheel: zoom the camera closer or farther
[weekly pit] information encryption + [answer] positive integer factorization prime factor
自定义限流注解
知识图谱之实体对齐二
SQL injection 2
Recyclerview GridLayout bisects the middle blank area
1_ Introduction to go language
Leetcode hot topic Hot 100 day 32: "minimum coverage substring"
Build your own application based on Google's open source tensorflow object detection API video object recognition system (IV)
[cloud lesson] EI lesson 47 Mrs offline data analysis - processing OBS data through Flink
(work record) March 11, 2020 to March 15, 2021