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
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
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) => {
...
})
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
.