javascript中this的用法

this的用法分几种情况 

1)如果调用this的function是对象的方法时(任何用作方法的函数都有效地传递了一个隐式的参数this,this指向调用函数的对象。 

如: 
 

Javascript代码  收藏代码
  1. var a  = {  
  2.             arg1: 1,  
  3.             arg2: 2,  
  4.             m : function(){  
  5.                  return this.arg1 + this.arg2; // 此处this指向a对象  
  6.             }  
  7.        }  



2)如果调用this的function只作为一个function存在时(一个函数作为函数儿不是方法调用的时候),this指向全局变量 

    

Javascript代码  收藏代码
  1. function a(){  
  2.           this.arg1 = 2;  //此处this指向window  
  3.      }  


     

值得注意的是,函数嵌套,this同样指向window: 
  

Javascript代码  收藏代码
  1. function a(){  
  2.           this.arg1 = 2;  //此处this指向window  
  3.           function b(){  
  4.                console.log(this)// 此处this同样指向window  
  5.           }  
  6.      }  



3)当一个函数嵌套在另外一个作为方法的函数里面是,前者的this(包括后者的this)都指向调用后者这个函数的对象 

    

Javascript代码  收藏代码
  1. var b = {  
  2.           arg1: 1,  
  3.           arg2: 2,  
  4.           m : function(){  
  5.                function emb(){  
  6.                     alert(this.arg1);    //此处this指向b对象  
  7.                }       
  8.           }  
  9.      }  
posted @ 2015-07-31 14:50  酸酸の柚子  阅读(104)  评论(0编辑  收藏  举报