当前位置:网站首页>ES6-箭头函数this指向
ES6-箭头函数this指向
2022-07-29 10:43:00 【setTimeout()】
箭头函数内部没有this指向,箭头函数内部this指向只能通过查找作用域链来决定,一旦使用箭头函数当前就不存在作用域链。
下面这样写会报错:
<body>
<script>
let Page = {
id: 123,
init: function() {
document.addEventListener('click', function(e) {
this.todo(e)
})
},
todo: function(type) {
console.log(`事件类型:${type},当前id:${this.id}`);
}
}
Page.init()
</script>
</body>如果改成下面这样:
<body>
<script>
let Page = {
id: 123,
init: function() {
document.addEventListener('click', (e) => {
this.todo(e)
})
},
todo: function(type) {
console.log(`事件类型:${type},当前id:${this.id}`);
}
}
Page.init()
</script>
</body>我们来分析一下上面这个代码,因为在箭头函数里面是没有this指向的,所以在click事件里面的回调函数就没有this,它就会去上一层也就是init去找,init是一个函数,它所在的对象是Page,所以最终作用域是Page,所以最终的输出结果是:

再来看下面这个:
<body>
<script>
let Page = {
id: 123,
init: () => {
document.addEventListener('click', (e) => {
this.todo(e)
})
},
todo: function(type) {
console.log(`事件类型:${type},当前id:${this.id}`);
}
}
Page.init()
</script>
</body>因为箭头函数是没有this指向的,所以在click事件里面的回调函数就没有this,它会去上一层init里面去找,init也是一个箭头函数也没有this指向又到Page,然后找定义Page对象的作用域链就是window。所以结果会报错。
一句话概括就是:
因为箭头函数是没有this指向的,所以在click事件里面的回调函数就没有this,它会去上一层init里面去找,init也是一个箭头函数也没有this指向又到Page,然后找定义Page对象的作用域链就是window。所以结果会报错。
一句话概括就是:“该函数所在作用域指向的对象”
边栏推荐
- [IVI] 17.1 debugging pit FAQ (compilation)
- 1. (map tools) detailed tutorial of acrgis desktop10.5 software installation
- StarRocks 技术内幕:实时更新与极速查询如何兼得
- A tour of grp:04 - GRP unary call unary call
- Mongodb aggregation statistics
- HTB-AdmirerToo
- Research on the realization of linear gradient circular progress bar
- The 2022 open atom global open source summit opened in Beijing
- VMware: use commands to update or upgrade VMware esxi hosts
- Easy to understand and explain the gradient descent method!
猜你喜欢
随机推荐
Data visualization design guide (information chart)
Implementation of college logistics repair application system based on SSM
A tour of grp:04 - GRP unary call unary call
Understand what a binary tree is (types, traversal methods, definitions of binary trees)
浅谈安科瑞灭弧式智慧用电在养老机构的应用
Understanding of Arduino circuit
R package pedquant realizes stock download and financial quantitative analysis
Follow teacher Li to learn online generation - matrix (continuously updated)
敏捷开发如何消减协作中的认知偏差?| 敏捷之道
一文搞懂什么是二叉树(二叉树的种类、遍历方式、定义)
2022cuda summer training camp Day2 practice
Explore SQL Server metadata (I)
remap_ Use of table in impdp
Roots of equations in R language dichotomy and Newton iteration
The 2022 open atom global open source summit opened in Beijing
从零开始Blazor Server(3)--添加cookie授权
R 语言 用黎曼和求近似 积分
Kunlunbase instruction manual (IV) real time synchronization of data from Oracle to kunlunbase
Use tidymodels to solve the binary logistic model
转转push的演化之路









