js中 ,this指向几种情况

180 阅读1分钟

1.在全局函数中,this指向window

function fn() {
      console.log(this);
    }
    fn()//window

2.在对象函数中,this指向调用者

    var obj = {
      name: '张三',
      thing: {
        age: 26,
        fn() {
          console.log(this);
        }
      }
    }
    console.log(obj.thing.fn())//this指向thing;

3.事件处理函数中,this指向事件源。

<button class="btn">点击查看this</button>

let btn = document.querySelector('.btn')
 btn.onclick = function () {
      console.log(this);
    }
    //this指向<button class="btn">点击查看this</button>

4.箭头函数中,this指向它父作用域中的this

<button class="btn">点击查看this</button>

let btn = document.querySelector('.btn')

    btn.onclick = function () {
      var fn = () => {
        console.log(this);
      }
      fn()
    } 
     //this指向<button class="btn">点击查看this</button>

5.构造函数中,this指向新创建的对象。

  function Fn(name, age) {
      this.name = name
      this.age = age
      console.log(this);
    }
    let fn = new Fn('张三', "27")
    //Fn {name: '张三', age: '27'}

6.定时器延时器中,this指向window。