1.全局作用域下
console.log(this);
2. 普通函数作用域下
var obj = {
fn1:function() {
console.log(this);
},
fn2:function(){
fn3()
}
}
function fn3() {
console.log(this);
}
fn3();//this->window
obj.fn1();//this->obj
obj.fn2();//this->window
3.箭头函数:由于没有 this 指向,箭头函数内打印 this 会指向上一层的 this
4.setTimeout()/setInterval() 内打印 this:
var obj = {
fn1:function() {
console.log(this);
setTimeout(function() {
console.log(this,"aaa"); //this->window
},500)
},
}
setTimeout(function() {
console.log(this,"aaa"); //this->window
},500)
obj.fn1();//this->obj
5.事件绑定中的this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="box" class="box">按钮</button>
</body>
<script>
let button = document.getElementById('box');
button.addEventListener('click', function () {
console.log("this", this); //this -> box
});
button.onmouseenter = function () {
console.log("onmouseenter", this); //this -> box
}
</script>
</html>