箭头函数 跟匿名函数this的指向问题

var id = 10;
function foo() {
    // 创建时 this->window

  this.id = 20;  // 等价于 window.id = 20
  let c = () => {
    console.log("id1:", this.id);  // 创建时父级  创建时 this->window
  };
  let d = function () {
    console.log("id2:", this.id); // 执行时本身
  }
  setTimeout(() => {
    console.log("id3:", this.id); // 创建时父级 创建时 this->window
  }, 100);
  c();
  d();
}
foo(); // 执行时this->window
console.log("id4:", this.id);

箭头函数 跟匿名函数this的指向问题_第1张图片

你可能感兴趣的:(javascript,前端,开发语言)