JavaScript 中的 this,永远指向最后调用它的那个对象。

this in JavaScript

var currentYear = {
  yaer: 2019,
  print: function () {
    console.log(this);
  }
};

currentYear.print() // 

下面是几个改变 this 指向的 example:

ES6 Array function

let year = 2019;

let nextYear = {
  year: 2020,

  func1: function () {
    console.log(this.year);
  },

  func2: function () {
    setTimeout(() => {
      this.func1()
    }, 100);
  }
};

nextYear.func2(); // 2020

new Operator

let year = 2019;

function Func () {
  this.year = 2018;
}

let lastYear = new Func();

console.log(lastYear.year); // 2018

apply, call, bind

let year = 2019;

let nextYear = {
  year: 2020,

  func1: function () {
    console.log(this.year);
  },

  func2: function () {
    setTimeout(function () {
      this.func1()
    }.apply(nextYear), 100);
    // }.call(nextYear), 100);
    // }.bind(nextYear)(), 100);
  }
};

nextYear.func2(); // 2020

_this = this

let year = 2019;

let nextYear = {
  year: 2020,

  func1: function () {
    console.log(this.year);
  },

  func2: function () {
    let _this = this;
    setTimeout(function () {
      _this.func1()
    }, 100);
  }
};

nextYear.func2(); // 2020