【JS】js中this的指向

JavaScript里,this的值在函数被调用的时候才会指定下来。这是个即强大又灵活的特点,但是需要花点时间弄清楚上下文什么的。但从所周知,这不是一件简单的事,尤其是在返回一个函数或将函数当参数传递的时候,实际上是指向调用它的对象

1.如果一个函数有this,但是它没有被上一级调用,那么this指向Window;

//直接打印
console.log(this) //window

//function声明函数
function bar () {console.log(this)}
bar() //window

//function声明函数赋给变量
var bar = function () {console.log(this)}
bar() //window

//自执行函数
(function () {console.log(this)})(); //window

2.如果一个函数中有this,这个有被上一级函数调用,那么this指向上一级的函数;

3.如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层对象所调用。

   this的指向也只是它上一级的对象

4.this永远指向的是最后调用它的对象,也就是看他执行的时候被谁调用;

//对象方法调用
var person = {
    run: function () {console.log(this)}
}
person.run() // person

//事件绑定
var btn = document.querySelector("button")
btn.onclick = function () {
    console.log(this) // btn
}
//事件监听
var btn = document.querySelector("button")
btn.addEventListener('click', function () {
   console.log(this) //btn
})

//jquery的ajax
 $.ajax({
    self: this,
    type:"get",
    url: url,
    async:true,
    success: function (res) {
        console.log(this) // this指向传入$.ajxa()中的对象
        console.log(self) // window
    }
   });
 //这里说明以下,将代码简写为$.ajax(obj) ,this指向obj,在obj中this指向window,
因为在在success方法中,独享obj调用自己,所以this指向obj

5.如果返回值是一个对象,那么this指向的是返回值的对象,如果返回值不是一个对象那么this指向函数的实例;

6.被嵌套的函数独立调用时,this默认板顶到window;

7.在构造函数或者构造函数原型对象中this指向构造函数的实例

//不使用new指向window
function Person (name) {
    console.log(this) // window
    this.name = name;
}
Person('inwe')
//使用new
function Person (name) {
      this.name = name
      console.log(this) //people
      self = this
  }
  var people = new Person('iwen')
  console.log(self === people) //true
//这里new改变了this指向,将this由window指向Person的实例对象people
发布了11 篇原创文章 · 获赞 18 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_35928292/article/details/82911985
今日推荐