首先,请牢记以下三点
1. this指向的,只可能是对象!
2.this指向谁,不取决于this写在哪!而是取决于函数在哪里进行调用。
3.this指向的对象,称之为函数的上下文context,也叫函数的调用者。
看一下具体的情况
1.通过函数名直接调用:this指向window
function funA(){
console.log(this);
}
// 通过函数名直接调用:this指向window
funA(); // this--->window
通过函数名直接调用
2.函数作为某个数组中的一个元素,通过数组下标进行调用:this指向这个数组,以上面的函数为例。
function funA(){
console.log(this);
}
var arr = [funA,1,2,3];
arr[0](); // this--->arr
通过数组下标进行调用
3.通过对象.函数名调用的:this指向这个对象
function funA() {
console.log(this)
}
var obj = {
name: "obj",
funA: funA
};
obj.funA(); // this--->obj
通过对象进行调用
4.通过DOM事件进行的调用,this指向页面中调用它的元素
假设页面中有一个id为div的元素
var div = document.getElementById('div')
div.onclick = function () {
console.log(this)
}
事件进行的调用
5.函数作为window内置函数的回调函数调用:this指向window( 如setInterval setTimeout 等)
function funA() {
console.log(this)
}
setTimeout(funA,1000);// this--->window
回调函数调用
6.函数作为构造函数,用new关键字调用时:this指向新new出的函数。
function funA() {
this.name = 'funA'
console.log(this.name)
}
var obj = {
name:'name',
fun:new funA(),
}
console.log(obj)
new关键字
上面是本人对于this指向的一些理解,如有错误或不足,望指出。