第149天:javascript中this的指向詳解

來源:互聯網
上載者:User

標籤:syn   lis   列印   $.ajax   事件   jquer   success   body   log   

js中的this指向十分重要,瞭解js中this指向是每一個學習js的人必學的知識點,今天沒事,正好總結了js中this的常見用法,喜歡的可以看看:

1、全域範圍或者普通函數中 this指向全域對象 window
 1 //直接列印 2 console.log(this) //window 3  4 //function聲明函數 5 function bar () {console.log(this)} 6 bar() //window 7  8 //function聲明函數賦給變數 9 var bar = function () {console.log(this)}10 bar() //window11 12 //自執行函數13 (function () {console.log(this)})(); //window
2、方法調用中誰調用this指向誰
 1 {console.log(this)} 2 } 3 person.run() // person 4  5 //事件綁定 6 var btn = document.querySelector("button") 7 btn.onclick = function () { 8     console.log(this) // btn 9 }10 //事件監聽11 var btn = document.querySelector("button")12 btn.addEventListener(‘click‘, function () {13    console.log(this) //btn14 })15 16 //jquery的ajax17  $.ajax({18     self: this,19     type:"get",20     url: url,21     async:true,22     success: function (res) {23         console.log(this) // this指向傳入$.ajxa()中的對象24         console.log(self) // window25     }26    });27  //這裡說明以下,將代碼簡寫為$.ajax(obj) ,this指向obj,在obj中this指向window,因為在在success方法中,獨享obj調用自己,所以this指向obj
3、在建構函式或者建構函式原型對象中this指向建構函式的執行個體
 1 //不使用new指向window 2 function Person (name) { 3     console.log(this) // window 4     this.name = name; 5 } 6 Person(‘inwe‘) 7 //使用new 8 function Person (name) { 9       this.name = name10       console.log(this) //people11       self = this12   }13   var people = new Person(‘iwen‘)14   console.log(self === people) //true15 //這裡new改變了this指向,將this由window指向Person的執行個體對象people

 

第149天: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.