详解this

归根结底,this的指向就是一句话:谁最终调用函数,this就指向谁,和定义函数没关系

1.this指向的,永远只可能是对象!
2.this指向谁,永远不取决于this写在哪,而是取决于函数在哪调用。
3.this指向的对象,称之为函数的上下文,即函数调用者。

下面看几种情况

通过函数名()直接调用:this指向window

1
2
3
4
>function func (){
console.log( this );
>}
>func(); //this --> window

通过 对象.函数名()调用的:this指向这个对象

1
2
3
4
5
6
7
8
9
10
11
12
>function func(){
console.log(this);
>}
>//狭义对象
>var obj = { };
>obj.func(); //this --> obj

>//广义对象
>document.getElementById('div').onclick = function(){
this.style.backgroundColor = "red";
>}; //this --> div

函数作为数组的一个元素,通过数组下标调用,this指向这个数组

1
2
3
4
5
>function func(){
console.log( this );
>}
>var arr = [ func , 2 , 3 , 4 ];
>arr[0](); //this --> arr

函数作为window内置函数的回调函数调用:this指向window(setInterval、serTimeout等)

1
2
3
4
>function func () {
console.log( this );
>}
>setTimeout(func,1000); // this --> window

函数作为构造函数,用new关键字调用的时候,this指向新new出来的对象

1
2
3
4
>function func (){
console.log( this );
>}
>var obj = new func(); // this -->new出来的obj

详解this
https://moewang0321.github.io/2019/08/09/2019-08-09-详解this/
作者
Moe Wang
发布于
2019年8月9日
许可协议