三种常见的this指向场景
①在对象方法内部this指向当前对面。例:
声明一个对象,对象里面有个say的方法,当在say方法内部this是指向当前对象也就是obj
var obj = {
name:"veblen",
say:function(){
return this.name;
}
}
console.log(obj.say()); //veblen
② 在事件处理函数内部this指向绑定的DOM对象 例:
<!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>
#box{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script>
box.onclick = function(){
console.log(this) //打印box这个节点
}
</script>
</html>
上面代码会打印box这个DOM对象
③在构造函数内部this指向实例对象 例:
function Fn() {
this.name = "veblen";
}
var o = new Fn();
console.log(o.name);//veblen
```