箭头函数中的 this 关键字

this keyword in arrow function

var cat = {
lives: 9,
jumps: () => {
console.log(this.lives)
 }
}

我听说箭头函数中的 'this' 关键字会指向父作用域,所以我尝试在节点的全局对象中放置一个 lives=9 的变量,但这似乎不起作用,我错过了什么吗?

var lives=9
var cat = {
lives: 9,
jumps: () => {
console.log(this.lives)
 }
}

箭头函数有一个词法this,这意味着函数内部this的值与函数外部this的值相同。

并不意味着this指向一个包含函数外部所有变量的对象。

const anObject = {
  aValue: "example value",
  aMethod: function() {
    console.log("aMethod", this.aValue);

    const arrow = () => {
      console.log("arrow", this.aValue);
    }
    
    arrow();
  }
}

anObject.aMethod();

const copyOfAMethod = anObject.aMethod;
copyOfAMethod();

因为aMethod作为anObject上的方法被调用,aMethod里面的this的值是anObject.

因为arrow是在aMethod里面声明的,所以this的值和aMethod的值是一样的。

如果该函数被复制到其他地方,因此它具有不同的 this 值,那么在调用副本时创建的箭头函数将具有相同的不同值。