情况 | this指向 |
---|---|
在普通函数中 | this指向window |
在自执行函数(也叫立即执行函数)中 | this指向window |
在计时器定时器函数中 | this指向window |
在事件调用函数时 | this指向触发当前事件的函数对象 |
在对象的方法中 | this指向调用方法的当前对象 |
在构造函数中 | this指向当前构造函数创建的实例对象,也就是new到的实例 |
在构造函数的原型对象中 | this依然指向构造函数的实例对象 |
在箭头函数中 | 本身没有this指向,但是可以继承父级的this,如果找不到父级,this指向window |
示例:
1.在普通函数中,this指向window
function fn(){
console.log(this);
}
fn();//普通函数调用后,this指向的是window
'use strict'
function fn(){
console.log(this);
}
fn();//严格模式情况下指向undefined,函数被window调用的话,必定指向window,无论是否严格模式
2.在自执行函数中,this指向window
(function(){
console.log(this);
})()
3.在定时器计时器中,指向window
setTimeout(function(){
console.log(this);
},0)
setInterval(function(){
console.log(this);
},0)
4.在事件调用函数中,this指向触发当前事件的对象
<body>
<button>点击我</button>
</body>
<script>
var btn=document.querySelector('button');
btn.onclick=function(){
console.log(this);//<button>点击我</button>
}
//另外的
//事件监听
var btn=document.querySelector('button');
btn.addEventListener('click',function(){
btn.style.backgroundColor='red';
console.log(this);//<button style="background-color:red;">点击我</button>
})
</script>
5.在对象调用方法中 ,this 指向当前对象
var obj={
name:'张三',
message:function(){
console.log(this.name+'是一个学生');//张三是一个学生
console.log(this);//this指向obj{name: '张三', message: ƒ}也就是obj这个对象
}
}
obj.message();
6.在构造函数中使用this,this指向当前构造函数创建的实例。(new 构造函数得到的对象)
7.在构造函数的原型对象中,this依然指向当前构造函数的实例对象
// 构造函数
// function Student (name,age){
// this.name=name;
// this.age=age;
// // console.log(this);//打印出来的是实例zs的属性 Student {name: '张三', age: 18}
// }
// 构造函数的原型对象
// Student.prototype.sing=function(){
// console.log('会唱歌');
// // console.log(this);//在zs.sing调用后打印出来,Student {name: '张三', age: 18}
// }
// var zs=new Student('张三',18);
// zs.sing();//会唱歌
8.
箭头函数中,箭头函数本身是没有this的,它的this是父级普通函数的this;
如果箭头函数没有父级函数,则this指向window.
var x=11;
var obj={
x:22,
say:()=>{
console.log(this.x);//11
console.log(this);//window
}
}
obj.say();
给箭头函数增加一个父级函数,this就指向了父级函数
var btn=document.querySelector('button');
btn.onclick=function(){
console.log(this);//<button>点击我</button>
var x=11;
var obj={
x:22,
say:()=>{
console.log(this.x);//undefined
console.log(this);///<button>点击我</button>
}
}
obj.say();
}
把父级函数也变成箭头函数,this都变成指向window
var btn=document.querySelector('button');
btn.onclick=()=>{
console.log(this);//window
var x=11;
var obj={
x:22,
say:()=>{
console.log(this.x);//undefined
console.log(this);//window
}
}
obj.say();
}
总结:
1.在普通函数中,this指向window;
2.在自执行函数(也叫立即执行函数)中,this指向window;
3.在计时器定时器函数中,this指向window;
4.在事件调用函数时,this指向触发当前事件的函数对象;
5.在对象的方法中,this指向调用方法的当前对象;
6.在构造函数中,this指向当前构造函数创建的实例对象,也就是new到的实例;
7.在构造函数的原型对象中,this依然指向构造函数的实例对象;
8.在箭头函数中,本身没有this指向,但是可以继承父级的this,如果找不到父级,this指向window。