標籤: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)})(); //window2、方法調用中誰調用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指向obj3、在建構函式或者建構函式原型對象中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的指向詳解