一、什么是this
1.解析器在调用函数时,美的都会向函数内部传递进一个隐含的参数
2.这个隐含的参数就是this,this是一个对象
3.这个对象我们称为函数执行的上下文对象
4.根据函数的调用方式不同,this会指向不同的对象
function fun(){
console.log(this);//[object Window]
}
fun();
//创建一个对象
var obj = {
name = "alex",
sayName : fun
};
console.log(obj.sayName == fun);//true
obj.sayName;//object
(1)以函数调用时:this永远都是window
(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>
<script type="text/javascript">
var name = "hello";
function fun() {
console.log(this.name);
}
fun();//(log name时)hello;(obj.name)happy;(obj2.name)sad;(this.name)hello;
var obj = {
name : 'happy',
sayName : fun//(log name时)hello;(obj.name)happy;(obj2.name)sad;(this.name)hppy;
};
obj.sayName();
var obj2 = {
name : 'sad',
sayName : fun//(log name时)hello;(obj.name)happy;(obj2.name)sad;(this.name)sad;
}
obj2.sayName();
</script>
</head>
<body>
</body>
</html>
二、e.target和this
<body>
<div>
123
</div>
</body>
<script>
var div = document.querySelector('div');
div.addEventListener('click',function(e){
console.log(this);//<div>123</div>
console.log(e.target);//<div>123</div>
})
</script>
<body>
<ul>
<li>abc</li>
<li>abc</li>
<li>abc</li>
<li>abc</li>
<li>abc</li>
</ul>
</body>
<script>
//当我点击li时
var ul = document.querySelector('ul');
ul.addEventListener('cilick',function() {
console.log(this);//<ul></ul>
console.log(e.target);<li>abc<li>
})
</script>
因此:得出结论
1.e.target返回的是触发事件的对象或元素
2.this返回的是绑定事件的对象或元素
3.有一个和this非常相似的属性叫做currentTarget,但同样有兼容性问题,一般不使用
三、this的指向问题
tips:一般情况下,this都指向调用它的对象
1.全局作用域或普通函数的调用,this都指向window对象(注意:定时器里面的this指向window)
2.方法调用中,谁调用this指向谁
3.构造函数中this指向构造函数
function Fun() {
console.log(this);
}
var fun = new Fun();//this指向fun
\