0

Does anyone know what happened to 'this'?

    console.log('check 1', this) //{activateLasers: ƒ, …}
    Object.keys(modelData).forEach(function(key, index1) {
    console.log('check 2', this) //undefined
user3662456
  • 267
  • 2
  • 11
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – John Montgomery Jan 16 '19 at 00:28

2 Answers2

2

The context of this changes inside map.

Array.prototype.map() takes a second argument to set what this refers to in the mapping function.

You can explicitly pass it to the map function to preserve the context.

array.map(function(i) {
  ...
} , this)

In your case

array.forEach(function(key, i) {
    ....
}, this)

Alternatively, you can use an ES6 arrow function to automatically preserve the current this context

array.map((i) => {
  ...
})
varoons
  • 3,807
  • 1
  • 16
  • 20
-1

It looks like you're writing code in strict mode. this is undefined because that's how the language works.

this in javascript is a syntactic construct. When you call a class or object method you usually do it in a way that looks like obj.method(). The language sees the syntactic pattern with the . and () and makes this obj inside method. If you ever don't see that pattern, (and are not using an => function, it should be a good cue that this might be undefined or window.

conartist6
  • 417
  • 4
  • 15