this指向問題

看題:

var myObject = {
   foo:"xiaohu",
   func:function(){
     var that = this;
     console.log(this.foo);//xiaohu
     console.log(that.foo);//xiaohu
  (function(){
     console.log(this == window);//true
     console.log(this.foo);//undefined
     console.log(that.foo);//xiaohu
   })()
  }
}
myObject.func()

外部函數func中,this函數指向的對象是myObject,因此that指向myObject
在內部函數中,this不再指向myObject。其結果是,this.name沒有在函數內部定義,相反指向到本地變量that保持的範圍內,並且可以訪問。內部函數的this將指向全局的window對象。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章