看題:
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對象。