標籤:function tag 錯誤 建立 return logs nbsp his console
1.對象的方法形式調用,fun.getAge()的this指向的是對象fun
var fun={ name:"lihui", age:23, getAge:function(){ console.log(fun.age);}}fun.getAge();//23
2.當在對象方法中內嵌函數,內嵌函數中的this便指向的是全域對象window,不是對象了
var fun={ name:"lihui", age:23, getAge:function(){ function getAgeFun(){ console.log(this.age); } return getAgeFun();}}fun.getAge();//underfined
要想在函數中把this指向對象需要在方法中將this賦值給一個變數,在函數中使用這個變數
var fun={ name:"xiaoming", age:23, getAge:function(){ var that=this; function getAgeFun(){ console.log(that.age); } return getAgeFun();}}fun.getAge();//23
之前經常在回呼函數中犯這種錯誤,就經常在success中建立函數,並在函數中直接this.xxx使用對象的參數,就會出錯
3.在對象方法中調用在外部建立的函數,函數中的this指向的也是window
function getAgeFun(){ console.log(this.age); }var fun={ name:"xiaoming", age:23, getAge:function(){ getAgeFun();}}fun.getAge();//underfined
4.在將對象方法賦值給其他變數,this值也是指向window
var fun={ name:"xiaoming", age:23, getAge:function(){ console.log(this.age); }}var fun2=fun.getAge;fun2();//underfined
js隨筆-函數方法中的this