1. 程式人生 > >第149天:javascript中this的指向詳解

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

doc ava 常見 每一個 document () 學習 知識 對象

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() //window
11 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) //btn 14 }) 15 16 //jquery的ajax 17 $.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) // window
25 } 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 = name
10       console.log(this) //people
11       self = this
12   }
13   var people = new Person(‘iwen‘)
14   console.log(self === people) //true
15 //這裏new改變了this指向,將this由window指向Person的實例對象people

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