I’m trying to add an element into an array with the push() method but apparently, I can’t access that array from the scope of my function.
Here’s a summary of my architecture :
class Test{
myArray;
aMethod() {
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
if(...){
this.myArray.push(myElement);
I know for sure that the problem come from the array. When executing the code, I have an error telling me that push isn’t a propriety of ‘undefined’. Plus, on Visual Code Studio, when I click once on the “myArray” in the function, I see that it’s not the same as the one that I declared at the top.
I’ve tried to declare it in various places but never successfully. I also tried to declare it like that myArray = [].
The strangest thing is that myElement is accessible from the scope of this function, so I tried to declare my array at the exact same place as so : let myArray… it didn’t worked.
Does anyone see something suspicious ?
Thank you for your time.
Advertisement
Answer
You need to understand how this works in JavaScript, I recommend reading this & object prototypes for more details
This is a solution:
class Test{
myArray;
aMethod() {
const myTestObj = this // store the Test instance in a variable myTestObj
Divs.forEach(
...
let myElement = ...;
div.addEventListener("click",
function(){
// In here `this` is bound to the global object
// because it will be invoked as a function, not a method, nor a constructor
if(...){
myTestObj.myArray.push(myElement); // Use myTestObj
Another solution would be:
class Test{
myArray;
aMethod() {
Divs.forEach(div => // Use an arrow function and only arrow functions in all the callbacks
// In here `this` is bound to the same object as in the upper scope
...
let myElement = ...;
div.addEventListener("click",
() => { // Arrow function here also
// In here `this` is bound to the same object as in the upper scope
if(...){
this.myArray.push(myElement); // Use this
Because arrow functions do not recreate a binding on this