当前位置:网站首页>箭头函数的this指向
箭头函数的this指向
2022-06-11 05:53:00 【不会秃头】
声明:call、apply、bind无法改变箭头函数的this指向
例如:
const fun1 = ()=>{
console.log(this === window)
}
const person = {
name:'tom'
}
fun1() // true
fun1.apply(person) // true
fun1.bind(person) // true
fun1.call(person) // true
可以看到箭头函数在这里初始的时候指向window,使用apply、bind、call来尝试改变它的指向,都失败了,始终指向window
结论:箭头函数指向为它的爷爷对象。也就是父级的父级对象。
证明:
const obj = {
name:'obj',
fun1:function (){
return setTimeout(()=>{
console.log(this.name)
},1000)
}
}
const person = {
name:'person',
age:'22'
}
obj.fun1() // obj
obj.fun1.apply(person) //person
可以看到,我们在setTimeout中调用箭头函数,setTimeout为全局函数,它指向的是window,然后我们是在obj对象里面的调用setTimeout,箭头函数的this指向父级的父级,在这里也就是指向了obj
前面说到,我们不能改变箭头函数的指向,但是我们可以改变它父级的父级的指向,由于箭头函数指向父级的父级,也就代表着我们改变了箭头函数的指向。例子里面我们改变了fun1的指向,成功改变了箭头函数的指向。
边栏推荐
- Functional interface lambda, elegant code development
- Dichotomy find template
- Super explanation
- How to use the markdown editor
- Do we really need conference headphones?
- Vscode plug-in development
- Warmly celebrate that yeyanxiu, senior consultant of Longzhi, won the title of "atlassian Certified Expert"
- [daily exercises] 1 Sum of two numbers
- Xposed bypasses 360 reinforcement to get a real classloader
- How to use perforce helix core with CI build server
猜你喜欢

Moteur de modèle de moteur thymeleaf

Write a list with kotlin

NFC Development -- the method of using NFC mobile phones as access control cards (II)

Twitter data collection (content, fans, keywords, etc.)

NDK R21 compiles ffmpeg 4.2.2 (x86, x86_64, armv7, armv8)

JIRA software annual summary: release of 12 important functions

NDK learning notes (XI) POSIX sockect local communication

Getting started with kotlin

那个酷爱写代码的少年后来怎么样了——走近华为云“瑶光少年”

Compliance management 101: processes, planning and challenges
随机推荐
Informatica: six steps of data quality management
Vscode plug-in development
Servlet
Sword finger offer 04: find in 2D array
Write a list with kotlin
"All in one" is a platform to solve all needs, and the era of operation and maintenance monitoring 3.0 has come
Elk log system practice (V): install vector and output data to es and Clickhouse cases
Growth Diary 01
Use of constructors
How to deal with message blackout and message sending failure of Aurora im
Clear function of ArrayList
Nlp-d46-nlp match D15
Warmly celebrate that yeyanxiu, senior consultant of Longzhi, won the title of "atlassian Certified Expert"
Functional interface lambda, elegant code development
[daily exercises] merge two ordered arrays
[元数据]LinkedIn-DataHub
Dism command usage summary
Jsonobject jsonarray for parsing
NDK learning notes (14) create an avi video player using avilib+window
[IOS development interview] operating system learning notes