在Javascript中,this这个关键字可以说是用的非常多,说他简单呢也很简单,说他难呢也很难,this到底是什么。下面我们来看看:
1、在一般函数方法中使用 this 指代全局对象
1 function hello(){
2 this.x = 1;
3 console.log(this.x)
4 }
5
6 hello();
7 //此时控制台打印1
2.作为对象方法调用,this 指代上级对象
1 function hello(){
2 console.log(this.x)
3 }
4
5 var s = {};
6 s.x = 1;
7 o.m = hello;
8 o.m();
9 //此时控制台打印1
3.作为构造函数调用,this 指代new 出的对象
1 function hello(){
2 this.x = 1;
3 }
4
5 var s = new hello();
6 console.log(s.x)
7 //运行结果为1,为了表明这是this不是全局对象,我们对代码做一些改变
8
9 var x = 2;
10 function hello(){
11 this.x = 1;
12 }
13
14 var o = new hello();
15 console.log(x)
4.apply 调用 ,apply方法作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数
1 var x = 0;
2 function hello(){
3 console.log(this.x)
4 }
5
6 var h = {};
7 h.x = 1;
8 h.m = hello;
9 h.m.apply(); //输出为0
10
11 h.m.apply(h) //输出1
以上就是常用的四种方法,大家要是不明白,可以把demo运行一下自己就知道了。