## this的指向取決是該函數被調用是的對象。函數
function test(){ var name=123; console.log(this.name); console.log(this); } test() ; //<empty string> window window.test() ; //<empty string> window
#### window 是js的全局對象。
#### 總結1:若是函數有this,可是沒有被上一級對象調用,這個時候window做爲全局對象,在非嚴格模式下,this指向的就是window。this
var o={ name:123, test:function(){ console.log(this.name); } } o.test() ; //123
#### 總結2:若是函數中有this,這個函數被上一級對象所調用,這是this,就是指向上一級對象。code
var o= { name:123, type:'boy', f: { name:456, test:function(){ console.log(this.name); //456 console.log(this.type); //undefined } } }; o.f.test() ;
#### 總結3:若是這個函數包含多個對象,儘管該函數被最外層對象調用,this指向的也是上一級對象。對象