js隨筆-函數方法中的this

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.