1.如下图所示,在行内绑定事件中,this指向window
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- 行内绑定事件 --> <div onclick="getInner(this)">gdfdfdfd</div> <script> function getInner(){ console.log(this); } </script> </body> </html>
2.动态绑定:this指向节点对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 100px;
height: 100px;
background: red;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box=document.getElementById("box");
box.onclick=function (){
console.log(this);
}
</script>
</body>
</html>
3.当在函数中时,this指向window
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function fn(){
console.log(this);
}
fn();
</script>
</body>
</html>
4.在对象中this指向对象本身
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let obj={name:"sa",age:30,fn:function(){
console.log(this);
}};
obj.fn();
</script>
</body>
</html>
案例解释:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let obj={
fn:function(){
console.log(this);
function test(){
console.log(this);
}
test();
}
}
obj.fn();
</script>
</body>
</html>
问题1:以上两个this指向相同吗?
答:不相同,虽然有时候this的指向可能相同,但是函数它们的本质上是不相同的
函数只有在执行的时候才会产生this指向,如果函数不执行,那么this的指向没有任何意义,即每一个this都是代表着一个函数的执行,
问题2:test函数中的this指向哪里呢?
答:window