⛳什么是this
⛳this指向
普通函数的this指向
谁调用就指向谁!!!
来看一些具体的例子👇👇👇
console.log(this) //window
function fn() {
console.log(this) //window
}
fn()
setTimeout(function () {
console.log(this) //window
}, 1000)
congsole.log()、函数调用fn()、setTimeout的完整写法👇👇👇
window.console.log(this) //window
function fn() {
console.log(this) //window
}
window.fn()
window.setTimeout(function () {
console.log(this) //window
}, 10000)
由此可见他们都是由window调用,所以this都指向window
其他:
document.querySelector('button').addEventListener('click', function () {
console.log(this) // 指向 button
})
const Class = {
name: 'One',
sayHi: function () {
console.log(this)
},
Student: {
name: '小铃',
sayHi: function () {
console.log(this)
},
}
}
Class.sayHi() //Class对象
Class.Student.sayHi() //Student对象 this指向被调用的最近的对象
注意:在严格模式下没有明确写明调用者时,this的值为undefined
// 严格模式
'use strict'
function fn() {
console.log(this);
}
fn() //undefined
window.fn() //window
箭头函数的this指向
实际箭头函数中不存在this!!!它绑定最近一层作用域中的this
具体案例👇👇👇
函数调用:
const fn = () => {
console.log(this)
}
fn() //window
箭头函数不存在this,往上一层作用域查找即全局作用域,那么此时this指向window对象
DOM节点绑定事件:
// 箭头函数,此时 this 指向 window
document.querySelector('button').addEventListener('click', () => {
console.log(this) // window
})
// 普通函数 this指向 button对象
document.querySelector('button').addEventListener('click', function () {
console.log(this) // window
})
原本this指向button按钮对象,当在箭头函数中,箭头函数不存在this,那么往上一层作用域this就指向了window对象
继续👇👇👇
const Class = {
name: 'One',
sayHi: () => {
console.log(this)
},
Student: {
name: '小铃',
sayHi: () => {
console.log(this)
},
}
}
Class.sayHi() //window
Class.Student.sayHi() //window
sayHi()为箭头函数不存在this,往上一层作用域即对象,对象内没有this再往外一层层找,找到最外一层即全局作用域,此时this指向window对象
注意
在了解this在不同场景的默认值后,关于如何改变this的指向可以看我的另一篇博客