

#yyds干货盘点#重新梳理箭头函数的this
source link: https://blog.51cto.com/u_11365839/5446142
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点#重新梳理箭头函数的this
原创记得之前分享过this的用法,是关于普通函数、构造函数的this,今天主要分享ES6箭头函数的this。先看普通函数下的this。
普通函数下的this:
- 在普通函数中的this总是代表它的直接调用者,在默认情况下,this指的是window,
- 在严格模式下,没有直接调用者的函数中的this是 undefined使用
- call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象
箭头函数中的this:
- 箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),
- 而不是执行时的对象, 定义它的时候,可能环境是window,也有可能是其他的。
console.log(this);
}
test(); //window
test是一个全局函数,也就是挂载在window对象下的 test()等价于window.test();
func: function () {
console.log(this);
setTimeout(function () {
console.log(this);
},0);
}
}
obj.func();
// obj,此时的this是obj对象
// window
func的宿主环境是obj,所以func里面的this是obj。 定时器中的函数,由于没有默认的宿主对象,所以this指向window 严格模式下的this:
'use strict';
console.log(this);
}
test();
//undefined
在严格模式下,没有直接调用者的函数中的this是 undefined
var obj={
say:function(){
console.log(this);
}
};
obj.say();
//obj
有直接调用者的this是它的调用者
say: function () {
setTimeout(() => {
console.log(this);
});
}
}
obj.say();
// obj
此时的 this继承自obj, 指的是定义它的对象obj, 而不是 window
say: function () {
var f1 = () => {
console.log(this); // obj
setTimeout(() => {
console.log(this); // obj
})
}
f1();
}
}
obj.say()
因为f1定义时所处的函数 中的 this是指的 obj, setTimeout中的箭头函数this继承自f1,所以不管有多层嵌套,都是 obj
say: function () {
var f1 = function () {
console.log(this);
setTimeout(() => {
console.log(this);
})
};
f1();
}
}
obj.say()
// window, f1调用时,没有宿主对象,默认是window
// window
箭头函数没有this的绑定,必须通过查找作用链来决定其值。如果箭头函数被非箭头函数包含,则this绑定的是最近以层的非箭头函数的this;否则。this的值会被设置为undefined。 箭头函数在定义的时候它所处的环境相当于是window, 所以在箭头函数内部的this函数window。
Recommend
-
6
#yyds干货盘点#THREE.BoxHelper的使用注意 原创 歆冉 2022-01-17 08:55:11...
-
9
1、Spring Data JPA1.1、pom<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"...
-
8
Windows 下搭建ActiveMQ环境 #yyds干货盘点# 原创 梁云亮 2022-01-17 11:25:27...
-
7
STP故障 1、根桥故障 在稳定的STP拓扑里面,非根桥会定期收到来自根桥的BPDU报文,如果根桥发生了故障,停止发送BPDU报文,下游交换机就无法收到来自根桥的BPDU报文。如果下游交换设备在MaxAge(default=20s)内没有收到BPDU报文,就会导致已经...
-
9
我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷
-
9
在css布局中,指定盒子的width和height,有时会见到calc函数,那么calc是什么,怎么用,今天就为大家分析一下。
-
6
实现响应式布局,一定会想到媒体查询,媒体查询有一个不太方便的地方,不同的设备都要写一套兼容方案。今天就分享一种新的解决方案——clamp()函数。
-
4
#yyds干货盘点#js中回调函数 精选 原创 简单来说:一个被当做参数的函数,就叫做回调函数。在JavaScript中,所有的函数都...
-
6
对象方法中,不适用箭头函数下面看一个例子:const obj = { name: '张三', getName() { return this.name }, getName1: () => { return this...
-
7
#yyds干货盘点#常用less函数 精选 原创 尼羲 2022-12-18 21:26:10...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK