What is the purpose of using "this" in the code provided below?

As a novice in JavaScript, I find myself struggling to fully grasp certain aspects of the script below;

I understand that Map, Player, and App are all classes, while map, player, and app represent instances of these classes;

However, why is the keyword "this" being used with the objects map and player instead of simply using var map = new Map() and var player = new Player()?

Any insights or guidance on this matter would be greatly appreciated!

var application;

var Application = function() 
  this.map = new Map();
  this.player = new Player();
};

(function() {
  application = new Application();
})();

Answer №1

var App = function() 
  var map = new Map(),
      player = new Player();
};

In this block of code, the variables map and player are only accessible within the function itself. Since there is no other code that accesses these variables, they will go out of scope once the function finishes executing.

var App = function() 
  this.map = new Map();
  this.player = new Player();
};

var app = new App();
app.map.foo();

The second piece of code illustrates how map and player are now properties of the instance of App, allowing them to be accessed outside the function by other functions or prototype functions associated with App.

Answer №2

In the code snippet, this is pointing to the object 'app'. By utilizing this, you can conveniently reach methods like app.map() and app.player().

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

Assigning an alternating class to each consecutive chat message, while ensuring that all messages share the same class

I currently have a basic node JS chat application set up. It utilizes express, mongodb, socket.io, and jQuery for the frontend. While everything is functional, I am looking to style every other message with a different color and alignment in the chat. Be ...

Combine various CSS files

If I have the following HTML structure : <div class="div"> <div class="sub-div"></div> <div class="sub-div"></div> <div class="extra-sub-div"></div> </div> ...

What is the process for adding a marker to an Angular Google Map using the autocomplete feature?

Can anyone help me with adding a marker on Google Angular Map using autocomplete search? I am able to retrieve the location in terms of latitude and longitude, but there seems to be an issue with adding the marker. Please review my code below: Controller ...

Encountered a buildkite error stating that the plugins file is either missing or invalid, resulting in a failure to locate the module 'xlsx' when executing a cypress test. Strangely

Encountering an issue while running my Cypress test on Buildkite. Here's the error message: Status: Downloaded newer image for cypress/included:6.1.0 [2022-01-31T10:32:13Z] Your pluginsFile is set to /e2e/cypress/plugins/index.js, but either the fil ...

Decipher and refine an array in JavaScript by filtering it

Within our existing codebase, we make use of Newtonsoft.Json.JsonWriter to generate a JavaScript array in the following format: [["1","zxc"],["2","fifa"],["3","fgh"]]. I am curious about whether Newtonsoft.Json offers any functionalities that could assi ...

The new method of calling datatable no longer supports the use of jquery's on('click') function

After updating my approach to creating a datatable in order to facilitate dynamic column generation, I included a column meant for revealing detailed information. function format (d) { console.log(d); var output = '' ; $.eac ...

Angular q.all: comparing immediate and delayed responses

Seeking advice on methodology: I currently utilize $q.all to handle multiple promises in a single return, processing all results as one request. For instance: $q.all([promise1(),promise2(),promise3(),promise(4),promise5()])..then(function(response){ ...} ...

The perplexing nature of the "this" keyword in JavaScript

Original Code - Version 1: const myobj = { a1 : 10, b1 : 20, c1 : 30, myfunc1 :function() { console.log(this) const myfunc2 = function () { let a2 =100 console.log(this) } myfunc2() } ...

Navigating through JSON data structures

Can anyone assist me with looping over an object that contains array values? I've been struggling with this for some time. My knowledge of JSON data structures is limited. var storeProducts = {"items": [ { "imgsrc": "https://cdn.shopify.com/s/fil ...

Is there a way to make the header reach the full width of the page?

Is there a way to make my header extend across the entire page? I attempted using margin-left and right, but it didn't yield the desired outcome. Header.css .header{ background: green; height: 70px; width: 100%; display: flex; ju ...

Tips for locating the script path within a specific JavaScript file

Is there a way to retrieve the script path of a JavaScript file within itself? I am looking to obtain something like "C:\files\MyProject\MyScripts\MyJavaScript.js" as a string. Any suggestions on how this can be achieved? ...

Strange behavior: JS object values disappear when accessed statically

I'm feeling puzzled. The issue at hand is that an object seems to lose its values within a loop based on the method of access. When accessed through variables, everything appears to be in order. However, when using static expressions identical to the ...

Difficulties arise when attempting to display an input within a Bootstrap modal

Upon clicking an icon, I aim to display a bootstrap modal prompting the user to input text and a date. I have adapted code from W3Schools to create the necessary form. Unfortunately, when the button is clicked, only the labels and text area are shown, not ...

Why is the imported package not being recognized in the namespace declaration of my Node.js TypeScript file?

Currently, I am utilizing the WebStorm IDE developed by JetBrains to modify a TypeScript file within a Node.js v8.6.0 project. The JavaScript version set for this project is JSX Harmony. In the beginning of the TypeScript source file, there is an import st ...

selection menu and advancement gauge

While working on my code, I have a task where I need to make the progress bar move a specific amount when a name is clicked based on the option's value. <!DOCTYPE html> <html> <head> <title>testinggg</title> &l ...

Removing an unnamed cookie

A mysterious cookie mysteriously appeared on my website, courtesy of Sharethis (value "sharethis_cookie_test"). This cookie is causing all sorts of session issues for me specifically on Chrome. Despite removing the sharethis plugin from my site, this pesky ...

Error: Required variable missing in AJAX Post request

When making an ajax call, I use the following code: o.open("POST",q,true); o.setRequestHeader("Content-type","application/x-www-form-urlencoded"); o.setRequestHeader("Content-length",p.length); o.setRequestHeader("Connection","close"); Here, q represent ...

Access the second DIV using JavaScript's getElementById method

What could be preventing me from displaying a Google map in the second DIV ID? I attempted changing my Map_canvas to Class with the same results. I am aiming to showcase a Google map in the second Div, map_canvas. The map functions within my jQueryMobile s ...

Gather information on LinkedIn connections

Looking to extract data from LinkedIn, specifically the connections of my own connections. I've successfully developed a Python script using BeautifulSoup and Selenium that is able to access the profiles of my connections and scrape their first 10 con ...

Populate the location in Javascript using PHP data

I have a MySQL database containing latitude and longitude values. I am attempting to display these pairs as markers on a map. The JavaScript code for the Google Maps locations is provided below: var locations = [{lat: 36.53256989, lng: -6.29461908}, {lat: ...