Making a single variable object as opposed to using multiple variables

In order to improve the code structure, I am looking to consolidate all properties into a JavaScript object instead of using multiple variables:

// Method 1
// This method gives an error as _inp cannot be accessed by input_value
// Uncaught TypeError: Cannot read property 'value' of undefined
var ref = {
_inp: input.target, 
input_value: _inp.value,
....
};

// Method 2
// Using this method works without any errors
var ref = {
_inp: input.target, 
input_value: input.target.value,
....
};


// Method 3
// This method also functions correctly.
var 
    _inp = input.target,
    input_value = _inp.value,

My question is, why does Method 3 work while Method 1 does not?

Answer â„–1

When looking at example 1, _inp is not just a variable, but rather a property of an object. This means that you can only access it through a reference to the object itself. It's important to note that this property will not be part of the object until the object actually exists, which happens after the object literal has been evaluated. For more information on this topic, check out Self-references in object literal declarations.

Answer â„–2

Since _inp is only populated with the value of input.target after going through the entire var ref = { ... }; statement, it does not exist when you attempt to utilize it.

Answer â„–3

The first method is unsuccessful because it references "_inp," a non-existent variable, and the reference object is not fully created (hence input_value: this._inp.value will not work either).

To effectively create objects and assign values to their properties, consider using a function with most of your existing code:

var ref = {
  _inp: input.target, 
  input_value: null,
  init: function()
  {
    this.input_value = this._inp.value;
  }
};
ref.init(); 
console.log(ref.input_value); // will hold the same value as input.target.value

Alternatively, it is common practice to create objects with all properties set to default values and pass arguments to their init function:

var ref = {
  _inp: null, 
  input_value: null,
  init: function(input)
  {
    if (input)
    {
      this._inp        = input.target;
      this.input_value = input.target.value;
    }
  }
};
var input = {target:{value:"foo"}};
ref.init(input);

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

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Tips on sending arguments to functions associated with ...mapActions...()?

After analyzing the passage below export default { methods: { ...mapActions(["updateData", "resetData"]); } } I wanted to include a parameter in the called functions. Unsure of the proper way to do this while still using the ...mapAction() call, ...

Show the percentage of completion on the progress bar while uploading with AJAX

I'm having trouble updating the current upload value on my progress bar in real-time. I know how to do it when the progress bar has stopped, but I can't get it to update continuously. xhr.upload.onprogress = function(e) { if (e.lengthComputa ...

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

Error: Unexpected identifier in jQuery ajax line

I'm currently encountering an issue with my jQuery ajax call that's throwing an "Uncaught SyntaxError: Unexpected identifier" error at line 3. For confidentiality reasons, I have omitted the original URL. However, even after removing the csrHost ...

Encountering a syntax error while attempting to send Node.js data to MySQL database

I am facing a problem with an SQL error that I just can't seem to figure out. Here is the error message: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual for MySQL server version for correct syntax near 'x Disney â ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

Tips for fixing the issue of "module ./response not found" in Node.js Express

Whenever I execute the command $ npm start this error message appears > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8feefcfce6e8e1e2eae1fbbccfbea1bfa1bf">[email protected]</a> start > nodemon server.js ...

Regular Expression: Identify specific characters at the start or end of a string

I am in need of a regular expression (regex) that can precisely match the char set 'AB' only if it is at the beginning or end of a string, and then replace it with an empty string. It is important to note that the regex should not match parts of ...

Display additional tiles within a compact container

I'm attempting to replicate the user interface used by foursquare! Positioning the map slightly off center like they have . I've figured out how to do one part but struggling with the second part. Initially, I loaded the map in a small div (t ...

Difficulty encountered when trying to template routes with more than one slash in Angular-route

I'm encountering difficulties with my Express+Jade+AngularJS[v1.2.22] application when attempting to access routes such as "mydomain.com/something/somethingelse" or "mydomain.com/something/another/last", which include one or more path subdivisions. T ...

What is the process for sending a request and obtaining a response from a REST API using JavaScript?

I have a private server set up on my computer with a built-in REST API. The base URL for the API is: . I am now looking to develop a client application for this server using the API. To authenticate on the server, the API endpoint is baseurl/login with the ...

Utilizing the power of Ajax for enhancing table sorting and filtering functionality

Having an issue using JQuery tablesorter to paginate a table with rows fetched from the database. //list players by points (default listing) $result=mysql_query("select * from players order by pts_total") or die(mysql_error()); echo "<table id='li ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

Connecting two COTURN servers for seamless communication

Currently, I have a total of 5 webRTC peers connected through the COTURN server (turnServer1). These peers are all behind symmetric NAT, requiring the use of the TURN server to establish connections. However, due to the media streams with audio and video b ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

How to harness the power of loops in JavaScript

Having trouble getting this code to repeat a CSS transition properly. for (var i=0 ; i<4 ; i++){ setTimeout(function() { $('#top-left').css('margin', '45px 0 0 45px'); $('#top-mid' ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

Shifting the entire page from left to right and back again

I am in search for a template that moves the page from left to right. If anyone can guide me on how to create this effect or provide a JavaScript example, I would greatly appreciate it. ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...