前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第149天:javascript中this的指向详解

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

作者头像
半指温柔乐
发布2018-09-11 10:03:14
3240
发布2018-09-11 10:03:14
举报
文章被收录于专栏:前端知识分享前端知识分享

js中的this指向十分重要,了解js中this指向是每一个学习js的人必学的知识点,今天没事,正好总结了js中this的常见用法,喜欢的可以看看:

1、全局作用域或者普通函数中this指向全局对象window

代码语言:javascript
复制
 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指向谁

代码语言:javascript
复制
 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指向构造函数的实例

代码语言:javascript
复制
 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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、全局作用域或者普通函数中this指向全局对象window。
  • 2、方法调用中谁调用this指向谁
  • 3、在构造函数或者构造函数原型对象中this指向构造函数的实例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档