newPromise / js-

0 stars 0 forks source link

es6的箭头函数 this 值 #30

Open newPromise opened 6 years ago

newPromise commented 6 years ago

es6 中的箭头函数 this 值的指向不同于使用 function 产生的 this 值, 在箭头函数中, this 值指向的是函数定义时所在的对象。 对于普通的函数而言,使用 this 值指向的是被调用的时候的位置。

所谓的定义位置以及调用位置

调用位置: 表示函数被谁调用 定义位置: 表明函数在哪里写的

newPromise commented 6 years ago
let person = {
    name: '张艺苇',
    getName: () => {
     // 箭头函数中的 this 值表明 this 指向的是全局 window
      console.log('我是被调用的this值', this.name);
    },
    getAnother: function () {
    // 这里 getAnother 是普通函数
      console.log('我是getAnother', this.name);
    }
  };
  var name = '张宁宁';
 // 箭头函数中的 this 是在这里被定义的,因此 this 指向的是全局 window
  person.getName(); // '张宁宁'
 // getAnother 是被 person 调用的,因此这里的 this 值指向了 person
  person.getAnother(); // '张艺苇'
newPromise commented 6 years ago

这个关于箭头函数的 this 值,自己理解的是有偏差的: 偏差主要是表现在理解函数中的

定义位置

关于 调用位置 很好理解, 主要是分析调用栈。而对于定义位置: 下面的函数:

let name = '张宁';
let person = {
  name: '张宁宁',
  age: 23,
  getName: () => {
    console.log(this.name);
  },
  // 这个 toGetName 的定义位置是在 person 对象内部被定义的
  toGetName: getName
}

调用:

person.getName() // '张宁'
person.toGetName() // ‘张宁宁’

关于定义位置不能仅仅被认为是调用位置: