Creating the 'THIS' value through a constructor without storing it in a variable

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.

Answer №1

Not assigning the new Player to a variable to create an object leaves uncertainty about what 'this' is pointing towards.

Using new Player generates an object with two references:

  • this inside the function
  • the return value of the function

The latter reference is discarded, while the former is copied to a variable named self.

This variable is encapsulated by the event handler function due to closures. For further details, refer to: How do JavaScript closures work?.

If I haven't assigned 'this.x' to a variable, where does it point to and how does it increment?

'this' is essentially assigned to a variable through the use of the new keyword.

I initially considered creating a closure

Indeed

However, creating a new player instance within a function may lead to its disposal once called and executed

Closures ensure that the variable remains active within the function that encloses it.

Answer №2

Within the realm of JavaScript, anything that does not fall under the category of primitive types (such as boolean, null, number, string, undefined) is regarded as an object. Hence, when you define a function, it essentially becomes an object.

By using the keyword new, you are essentially creating a new instance of the Object. Each individual instance comes equipped with its own built-in this variable for reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Find the differences between two arrays and eliminate any matching items

In my Vue project, I am working with two arrays. The first array, TempId, contains the following data: [{"id":47},{"id":45},{"id":48}] The second array is called multiprices and it looks like this: multiprices: [ { ...

What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking. There is a predefined class: .red { background-color: red; } The goal is to dynamically apply this class whe ...

AJAX with JQuery: retrieving data from returned objects

I am facing an issue while trying to access data retrieved from an Ajax call that I made using the Steam API. The data is successfully returned as I have verified by console logging it. However, whenever I attempt to access the data, I receive an 'und ...

Simple method to toggle visibility of forms using an AngularJS Button

I am hoping to create a seamless user experience by having a Login/Register button that, when clicked, reveals the corresponding form without validating anything in the JavaScript code. The goal is to have the form slide out when the button is clicked, and ...

Substitute the aircraft in the cosmos with ThreeJS

I am trying to adjust the position of a plane in ThreeJS to a specific Z value. Using shapeBufferGeometry with vectors containing x, y, and z values. Below is my code and the current output. I want the white plane to align with the aqua lines. The code ...

"AngularJS directive mandating the use of the required attribute for internal control

I've encountered a challenge with this specific issue. We are using a directive called deeplink, which contains the following code: restrict: 'E', require: 'ngModel', scope: { smDropdown: '=smDeeplinkDropdown', s ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

Creating a button that integrates an image within a single div element

Currently, I understand the code: $('#leftDev').css("background-image", "url(img/1.png) "); will set the entire background of my leftDiv to display "1.png". However, I would like to position this image as a regular picture within the div and no ...

Executing a function after a return statement in Vue JS

I have a function that allows me to delete an account by calling the deleteAccount function. After successfully deleting the account, I would like the user to be automatically logged out from the vuex store. Although I currently use setTimeout as a workaro ...

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

Tips for handling numerous requests using Express.JS

I am currently working on an Angular 6 + Express.JS application and have encountered a problem. When multiple requests are made simultaneously, especially when there are more than 4 requests, all of them sometimes respond with a 404 error or get cancelled. ...

Transmit a file using multipart with XMLHttpRequest

Is it possible to use XMLHttpRequest to send a multipart file to a servlet? I am currently working on a form that needs to be submitted as multipart, but I am not receiving a response after successfully uploading it. It is important that the process happe ...

Close ui-bootstrap typeahead menu only when a row is manually chosen

I have set up this jsBin to show the problem I am facing. When you visit the link and try to type "Five," the expected behavior would be to type "Five" and then press tab. However, in this case, you need to type "Five" and then either escape or click outsi ...

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Is there a way for me to retrieve the information within this function? It seems like it may be a promise, but I am uncertain

I need help extracting the data from doc.data and sending it to another component based on the dropdown selection. It appears that the data is in promise format, and despite trying async/await, I am struggling to access it. Can anyone guide me on how to ...

Manipulating child classes using jQuery

I am struggling to display an X icon next to a tab on my page when the tab is clicked, but I am facing difficulties in toggling its visibility. The issue arises when trying to access the span element within the tabs. $('.tabs .tab-links a').on(& ...

Module Augmentation for extending Material UI theme is not functioning as expected

I'm having trouble expanding upon the Theme with Material UI because an error keeps popping up, indicating that I am not extending it correctly. The error message states: Property 'layout' is missing in type 'Palette' but required ...

Incorporating external files into Javascript code may cause issues with its functionality

Currently, I have a fully developed PHP theme that I am in the process of designing. Within this theme, I have integrated an image slideshow plugin to enhance its functionality. The following code represents the implementation of the image slideshow: &l ...

Enter information to accompany your images in the description box

After browsing through numerous websites tonight, I stumbled upon this code. My goal is to create a photo upload page on Google Drive and set up a dropbox for it. I'm facing an issue where the information inputted into my placeholder box (city and ye ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...