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

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
原文地址:https://www.cnblogs.com/le220/p/8310641.html