I've been exploring constructors in Javascript and came up with some code that's a bit confusing to me.
function anotherFunction() {
new Player(0, 0);
}
function Player(x, y){
let self = this;
this.x = x;
this.y = y;
window.addEventListener('click', function() {
self.x++;
self.y++;
console.log('x:' + self.x + 'y: ' + self.y);
});
}
anotherFunction();
I've defined a constructor that is called when using the New keyword. It sets the values of x and y and attaches an event listener to the window object.
I'm puzzled about where the new Player instance is stored and how it accesses and increments its properties this.x and this.y.
I didn't assign the new Player to a variable to create an object, so I'm unsure what THIS is pointing to?
I omitted:
let obj = new Player(0, 0);
In this case, this.x would reference the object 'obj', x property. So, without assignment to a variable, where does this.x point to and how does it keep incrementing?
I considered the possibility of creating a closure, but since I'm creating a new player instance inside a function that I assume gets discarded once executed, I don't understand how it maintains a reference to the x and y properties without being assigned to a variable.