從零開始學習前端JAVASCRIPT — 11、JavaScript基礎this指向的四種情況

來源:互聯網
上載者:User

標籤:class   注意   全域   function   color   new   this   構造   mil   

JavaScript中this的四種情況(非strict 模式)

 

1、當this所在函數是事件處理函數時,this指向事件來源。
2、當this所在函數是建構函式時,this指向new出來的對象。
3、this所在函數的所屬對象是誰,this指向函數所屬對象。
4、當this所在函數沒有所屬對象,this指向window對象

<!DOCTYPE html>  <html>      <head>          <meta charset="utf-8" />          <title></title>      </head>      <body>            <div id="box" class="box" style="height: 100px; width:100px; background:#f3f3f3;"></div>    </body>  </html>    <script type="text/javascript">  //this  //1、當this所在函數是事件處理函數時,this是事件來源。  document.getElementById("box").onclick = function(){   console.log(this); //this就是div.box }    //2、當this所在函數是建構函式時,this是new出來的對象。  function Person(name){      this.name = name;//this就是new出來的對象zhaosi    console.log(this.name)    this.eat = function(){          console.log(this.name+"is eatting");    }  }  var zhaosi = new Person("趙四");    // 3、this所在函數的所屬對象是誰,this就是誰。  function Person(name){   this.name = name;//就是new出來的對象liuneng this.eat = function(){       console.log(this.name+"is eatting");;//這個this是誰,誰調用eat,或者說調用eat時,前面的對象是誰,this就是誰   }  }  var liuneng = new Person("劉能");  liuneng.eat();//這句話執行時,eat函數內部的this就是p1  var laoqi = new Person("老七");  laoqi.eat();//這句話執行時,eat函數內部的this就是p2    //4、當this所在函數沒有所屬對象,this是window對象。全域變數都是window對象的屬性。 function test(){      console.log(this);//這個this就是window  }    test();//window對象可以省略,所以,這句話就等價於window.test();    //全域變數是window對象的屬性  var t = "大腳";    console.log(window.t);    var obj = {      name:"李四"}    console.log(window.obj.name);    //this轉移是經常碰到的問題  //1)、注意區分this所在函數調用時的隸屬對象  //2)、如果不希望被this折磨可以選用ES6中的箭頭函數。    </script> 

 

從零開始學習前端JAVASCRIPT — 11、JavaScript基礎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.