This values for arrow functions [duplicate]

巧了我就是萌 提交于 2019-11-27 23:55:30

Let's transform into the equivalent ES5 code:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: function(){return console.log(this)}.bind(this)
  }
}

Remember that this depends on how you call the function. The outer this isn't inside a function, so it will default to undefined in strict mode.

Simplified scenario below:

console.log(this) // undefined

var test = {
  a: this // same `this` as above
}

You are defining the arrow function in the same scope that you defined var test. If you are defining test in the global scope, then the arrow function's context will be the global scope too.

If you are defining test inside of a method, the arrow function will share the method's context.

function method() {
  const self = this;

  const test = {
    foo: () => console.log(self === this);
  }

  test.foo()
  // console: true
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!