JavaScript 普通函数、箭头函数和this

  • 作为对象属性的普通函数,this 绑定为该对象。

  • 作为回调函数的普通函数,this 绑定为被触发对象。

  • 除了 call、apply、bind 以外能指定 this 参数,其余调用普通函数的地方,this 都绑定为全局对象。

  • 箭头函数没有自己的 this,也就是说没有自己的定义域。进一步说,就是会绑定定义时上层代码块的 this。

function Timer() {
    this.s1 = 0;
    this.s2 = 0;
    // 箭头函数
    setInterval(() => this.s1++, 1000);
    // 普通函数
    setInterval(function () {
        this.s2++;
    }, 1000);
}

假如 var timer = new Timer();
此时 timer.s1 可以正常绑定,.s2 被绑定到了全局对象。

再假如,直接调用函数 Timer(),此时 s1 也被绑定到了全局对象。
  • 即使作为对象方法,箭头函数内部的 this 也是指向的全局对象。所以箭头函数不适合作为函数方法。
  • 作为回调函数的箭头函数,this 绑定为全局对象。所以箭头函数不适合动态指定 this 的场合。
var x = 10;

let foo = {
  x: 20,

  // Dynamic `this`.
  bar() {
    return this.x;
  },

  // Lexical `this`.
  baz: () => this.x,

  qux() {
    // Lexical this within the invocation.
    let arrow = () => this.x;

    return arrow();
  },
};

console.log(
  foo.bar(), // 20, from `foo`
  foo.baz(), // 10, from global
  foo.qux(), // 20, from `foo` and arrow
);