es6 箭头函数的this 指向问题

箭头函数体内的this,就是定义时,函数所在的对象,而不是调用时所在的对象。

var foo = () => {
  console.log(this.id);
}

var id = 1;

foo(); // 输出1 // this 的指向一直是指向 window

foo.call({ id: 2 }); // 输出1  // this 的指向一直是指向 window

普通函数体内的this,指向调用时所在的对象。

function foo() 
{
    console.log(this.id);
}

var id = 1;

foo(); // 输出1 this指向 window

foo.call({ id: 2 }); // 输出2  这里是{ id: 2 }调用 foo,所以 this的指向是 { id: 2 }这个对象,因此 console.log(this.id); 的输出值是 2

猜你喜欢

转载自blog.csdn.net/weixin_39090097/article/details/84138850