this的指向问题:
本文详细解释this关键字在不同场景下的指向问题。
this的概念
this是一个关键字
主要介绍函数内的this
概念:
函数内的this和函数在哪定义的没有关系,和函数怎么定义也没有关系。
*! 只看函数如何被调用的(箭头函数除外)
<style>
div {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<div id="div"></div>
<script>
function fn() {
console.log(this);
console.log("================");
}
// 普通调用
fn()//this 指向的是window
// 对象调用
var obj = {
a: 12,
fun: fn,
name: 'jack'
}
obj.fun()//this指向的是obj
obj['fun']()
// 数组调用
var arr = [fn, 12, 'tom']
arr[0]()//this指向的是arr
// 定时器调用
setTimeout(function () {
fn()//this指向的是window
}, 500);
setInterval(function () {
fn()//this指向的是window
}, 500);
setTimeout(fn(), 90)//this指向的是window
// 事件处理函数
div.onclick = fn//this指向的是事件源
// 0级绑定事件
div.onclick = function () {
console.log(this);//this指向的是***事件源***,不是事件目标。
console.log('=============');
}
// 二级绑定事件
div.addEventListener('mousemove', function () { console.log(this); })//this指向的是事件源
// 自执行函数
;(function () {
console.log('自执行函数');
console.log(this);//this指向的是window
})()
</script>
// 总结
/*
普通调用、定时器调用、自执行调用----this指向的是window
对象调用------this指向的是对象名
数组调用------this指向的是数组名
事件处理函数调用------this指向的是事件源 */