avaScript的this关键字非常灵活!
this 返回的总是对象;
即返回属性或方法“当前”所在的对象
1 var o1={ 2 name:'apple', 3 age:100, 4 msg:function(){ 5 return '显示name和age信息:'+'name: '+this.name+', age: '+this.age; 6 } 7 }; 8 //针对msg中的this进行研究: 9 console.log(o1.msg());//this 指向当前对象o1 10 var o2={ 11 name:'blue', 12 age:1000 13 }; 14 o2.msg=o1.msg; 15 console.log(o2.msg());//this 指向当前对象o2
当o1.msg()时,this指向o1;而o2.msg()时,this指向o2。也就是this指向的是“当前”环境运行时所在的对象。
运行结果:
将函数提出来,更形象的表示:
1 console.log('---'); 2 function f(){ 3 console.log(this.name1); 4 } 5 var o3={ 6 name1:'alice', 7 info:f 8 }; 9 var o4={ 10 name1:'boy', 11 info:f 12 }; 13 f();//undefined 14 o3.info();//alice 15 o4.info();//boy
f():this指向顶层对象window;o3.info():this指向的是o3;o4.info():this指向的是o4。即this总是指向“当前”运行时所在的对象。
运行结果:
如果我们在全局环境中,将对象中的方法赋值给变量。以本文最上面代码o1.msg示例:
1 var name='abc'; 2 var age=1; 3 var test1=o1.msg; 4 console.log(test1());//此时this指向顶层对象window
此时test1():this指向的是window
运行结果:
由上面的这些例子,我们可以“粗略”的认为:每个函数中都存在着this,它总是指向当前运行环境的对象。
全局环境下的this:指向顶层对象window
1 function test2(){ 2 if(this === window){ 3 console.log('此时this 指向顶层对象window'); 4 } 5 } 6 test2();
运行结果:
构造函数中的this:
指向实例化的对象
1 function Test3(num){