在JavaScript中很多人对this的指向不是很明白,在这里对这个知识点进行一下总结。
总的来说this的指向分为以下四种情况:
1.全局作用域或者普通函数this的指向是window
Example:
//全局作用域
console.log(this); //指向window
//普通函数
function a(){
console.log(this);
}
a(); //指向widow
2.有事件源的指向事件源本身
document.onclick(){
console.log(this); //this指向document
}
需要注意的是下面这种情况:
document.onclick(){
function a(){
console.log(this);
}
a(); //指向window 因为a()属于普通函数
}
3.在定时器下除es6的箭头函数外,this指向window
document.onclick = function () {
function a() {
console.log(this);
}
a(); //window
}
//在es6的箭头函数下this指向的是最靠近它的父级
document.onclick(){
setInterval(()=>{
console.log(this); //this指向setInterval的父级document
},100);
}
4.在对象(什么是对象)下,this指向的是本身
var json = {
a:function(){
console.log(this);//object 也就是json
}
}
//构造函数为例
function animal(name){
this.name = name;
console.log(this); //指向windos
}
animal("dog"); //windos
function animal(name){
this.name = name;
console.log(this);//指向animal
}
//对象实例化后改变了this的指向,由原本指向window改为指向animal
var ani = new animal("dog");
以上是我对this的一些简单的理解,如有错误的地方,希望能够指出来。