I am currently experimenting with constructors in Javascript and wrote some code but can't quite understand it myself
function someOtherFunction() {
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);
});
}
someOtherFunction();
I have created a constructor which gets executed when using the New keyword which then sets the x and y value and also binds an event listener to the window object.
I am confused as to where new Player is actually stored and how it refers to this.x and this.y and increases its value.
I did not assign the new Player to a variable to create an object so i am not to sure what the THIS is point towards?
I didn't write:
let a = new Player(0, 0);
Which this.x would then refer to the object 'a', x property. so where does this.x refer to when i haven't assigned it to a variable and how does it keep incrementing?
I thought maybe i created a closure, but i am creating a new instance of a player inside a function which i assume get's discarded once called and executed so how is it keeping a reference to the objects x and y property without assignment to some variable.