I have the following chunk of Typescript code in a function, with variableInQuestion = 0
being defined outside of the function:
console.log(this.variableInQuestion);
this.arrayOfObjects.each(function(thing) {
if (this.variableInQuestion !== undefined && thing.property == this.variableInQuestion) {
...
}
});
The problem is that the console.log line prints out exactly what I would expect (the default value of 0), but I get an error for the third line saying Cannot read properties of undefined (reading 'variableInQuestion') at [[[location of the first variableInQuestion in the third line]]]
. I don’t understand why it’s giving me a "cannot read properties of undefined" error while I am testing to see if it’s undefined.
EDIT: the .each
thing is specific to the array of objects in question; that’s not the issue. If I run the following…
console.log(this.variableInQuestion);
this.arrayOfObjects.each(function(thing) {
if (0 !== undefined && thing.property == 0) {
...
}
});
It works exactly as I’d expect.
2
Answers
The way to address this problem is as follows:
Special thanks to Pointy for identifying the problem!
If you
console.log
your data, you’ll seebecause
forEach
doesn’t keepthis
value.Either use lambda
, keep
this
value, or provide
thisArg
intoforEach
(dunno about.each
butArray.prototype.forEach supports that
)