0

Sup folks,

I have a lifecycle hook declared inside component like this:

export default {
  created: function() {
    console.log(this)
  },
}

console prints vueComponent, all good.

However if I change it to an arrow function like so:

export default {
  created: () => {
    console.log(this)
  },
}

now this is undefined.

Why? Thanks in advance for help.

flamasterrr
  • 269
  • 3
  • 12
  • 2
    There’s a call-out box in the [documentation](https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks) with the first sentence: `Don’t use arrow functions... Since an arrow function doesn’t have a this` – Mark Nov 26 '19 at 16:16
  • 2
    Possible duplicate of [VueJS: why is "this" undefined?](https://stackoverflow.com/questions/43929650/vuejs-why-is-this-undefined) – Ayrton Nov 26 '19 at 16:24

2 Answers2

3

The this keyword becomes unavailable in that scenario because arrow functions have no this context, so javascript looks in the outer scopes for that value. That means that if you use arrow functions, this will often be either undefined or take on an undesirable value.

That is also stated in the docs. Inside your Vue instances, avoid arrow functions.

tony19
  • 125,647
  • 18
  • 229
  • 307
Ayrton
  • 2,218
  • 1
  • 14
  • 25
2

It is already stated in the docs

from the docs

tony19
  • 125,647
  • 18
  • 229
  • 307
AbdulAzeez Olanrewaju
  • 976
  • 1
  • 13
  • 32