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