Various methods of defining JavaScript objects

As someone who is new to delving into JavaScript, I find myself pondering over how objects are defined within the code snippet provided below.

I noticed that in one instance, the domStrings object is set as domStrings=, while in another instance, the returning object is defined as getinput:function(). What exactly sets these two definitions apart? Moreover, why does altering the returning object to getinput=function lead to functionality issues? I would greatly appreciate some clarity on this matter.

var UIcontroller = (function() {
  var domStrings = {
    inputType: '.add__type',
    inputDescription: '.add__description',
    inputValue: '.add__value',
    addButton: '.add__btn'
  }
  return {
    getinput: function() {
      return {
        type: document.querySelector(domStrings.inputType).value,
        description: document.querySelector(domStrings.inputDescription).value,
        value: document.querySelector(domStrings.inputValue).value
      };
    },

    getDomStrings: function() {
      return domStrings;
    }
  }
})();

Answer №1

When it comes to the var domStrings, it is essentially an object which consists of keys and values. The keys include inputType, inputDescription, inputValue, and addButton, each corresponding to their respective values. These can be accessed using domStrings.inputType for example.

Your function, on the other hand, is generating a new object with return {}, where getinput acts as a key within this object, hence its specific definition in this context.

Answer №2

The concept you are observing is known as an immediately invoked function expression (or IIFE, pronounced "iffy"). It serves as a workaround in JavaScript (ECMAScript 5) to prevent hoisting and establish closures.

In the provided example, the variable domString is assigned using the equals sign, with the right side utilizing object literal syntax. The two functions returned in the return statement are declared as properties within the object literal domStrings, similar to how 'inputType:' would be included. The distinction lies in the fact that the values of these properties in the return statement are functions rather than strings. In JavaScript, variables and object properties can store functions as their values.

Within the context of your example, domStrings serves as a private property of the UIcontroller function, only accessible within the function itself. It exposes two public functions: getDomStrings and getinput, which are returned for use by callers during instantiation.

While these methods have access to domStrings, external entities cannot interact with it unless a reference to domStrings is also included in the return statement.

You could invoke UIcontroller.getDomStrings() and UIcontroller.getinput(), but calling UIcontroller.domStrings directly would not work. Making domStrings part of the return statement would transform it into a public property of UIcontroller, open to modification by any entity.

I trust this explanation clarifies the concept for you effectively.

Happy programming!

Answer №3

In completing this task, two key elements are being addressed:

var domStrings = {
    inputType: '.add__type',
    inputDescription: '.add__description',
    inputValue: '.add__value',
    addButton: '.add__btn'
  }

The variable domstrings is initialized as var domStrings and then assigned with =.

This action establishes a memory location where an object has just been created.

An object in JavaScript functions like a dictionary, housing key:value pairs where the key can be a string or number.

Object declaration follows this syntax: { 'key': 'value' .... }.

The value within an object can encompass various JS types such as strings, numbers, void, functions, or other objects.

A separate variable can point to the same object in memory:

var a = domStrings;
a.inputType /// '.add__type'

If a new assignment is made to domStrings:

domStrings = "nope"

domStrings now directs to a distinct memory location:

domStrings.inputType // undefined - "nope" lacks a property inputType

a still points back to the original object:

a.inputType // '.add__type'

Therefore, by making that statement, a variable (domStrings) is declared, an object is generated in memory, and then the object is assigned to the variable, creating a reference to it.

Does this clarification address your initial query?

The second aspect revolves around what's referred to as a closure. It represents an IIFE - "Immediately Invoked Function Execution" - functioning as a secluded environment akin to a black hole singularity. The internal operations within this function closure have visibility internally; however, when viewed from outside, the external value of UIController appears as:

{
  getinput:() => {...},
  getDomStrings: () => domstrings
}

The getDomStrings function embedded within UIController accesses the domstrings variable, offering an outward pointer while still confined within the closure itself.

Similarly, the getInput function taps into this information to determine the object returned during its execution.

Certain code/data dissemination between functions inside a closure is feasible, with embargoed access from outside unless a referential passageway like getDomStrings is employed.

...

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

What is the best way to stop a series of Ajax promises from continuing?

Managing multiple ajax requests that are dependent on each other can be tricky, especially when you need to stop the chain if one of the requests returns false. Check out this sample code snippet below: // Implementing a promise chain return this.getBan ...

Tips for calculating the distance from the cursor position to the visible area

Is there a way to determine the cursor's offset from the top of a textarea's view rather than its position? While e.target.selectionStart provides the cursor position, $el.scrollTop gives the scroll offset of the textarea. Any suggestions on ho ...

Is there a way to use jQuery to automatically make a field stand out visually?

I am looking for a way to make a text field automatically underline as the user types. The line should follow along with the characters in real-time, and when the user moves away from the field, I want the line to fill up the entire width. This signifies t ...

Comet spinning in orbit around celestial body

I need help creating a game where an object (comet) can fly and rotate around another object (planet) in orbit. Currently, I have managed to make the comet move and turn towards the planet, but I am struggling to figure out how to make it start rotating ar ...

Recording web browser network traffic using JavaScript

Is there a method in webdriverio that allows me to capture and validate the response of API calls made by the browser while loading data for my automated tests? https://i.sstatic.net/TMExU.png ...

Troubleshooting a JS promise issue with Kriskowal's Q library

I have been working with the kriskowal/q module to create a promise, but I am encountering an issue where it does not enter any function paths - neither the happy path nor the error path. Below is the class where I create the promise: var Q = require(&ap ...

The popover feature on a vertically scrolling table is malfunctioning as it does not follow the scroll of the triggered element, remaining static instead

I'm currently working on a project involving a vertical scrollable table where I need to trigger a popover on click. However, as I scroll up or down the table, the popover remains in the same position. Ideally, I'd like the popover to move along ...

One way to display GIFs sequentially without preloading them is by using JavaScript

On my website, I'm trying to display five animated gifs sequentially. I want gif2 to appear and start its animation only after gif1 has finished its animation. However, the code I'm using is giving me some unexpected behavior. While it works corr ...

Changing the value in sessionStorage does not trigger the onChange event (Next.js)

When I use a custom hook to load data from session storage into an input field, I noticed that the onChange() function doesn't trigger if I delete the entire content of the input. However, it works fine if I add or delete just one character. This issu ...

Utilize jQuery to style the background of the webpage, while excluding the Modal element when using Bootstrap

I'm currently working on implementing foggy.js () to create a blurred background effect for Bootstrap's Modal. While I've successfully blurred all elements in the background, the Modal Popup itself is also appearing blurry. So my question is ...

AngularJS error: Cannot find provider for $scopeProvider due to $scope not being injected in the service

I've come across a puzzling issue while working with AngularJS and dependency injection that seems to be common among many developers. When I attempt to inject a service into a controller in my AngularJS app, I encounter an error stating: Unknown prov ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

Elevate the elegance of your switch statement

After researching alternatives to using a switch statement, I found some interesting methods for simplifying or converting it into an object literal. You can check out these resources for more information: Rewriting Javascript: Replacing the Switch Statem ...

Is it possible to include ternary in the "homepage" section of the package.json file?

When making API calls in production, they will be on the same domain as where my app is hosted, so it's necessary to include "homepage": "." in the package.json. However, when working locally from localhost, I need to make API calls to the production ...

Clicking the button will remove any previously applied CSS style using jQuery

Is there a way to remove the background color that was applied to a previously clicked button when clicking on another button? The current code successfully changes the background color of the clicked button upon hover, but it doesn't reset or remove ...

Implementing a Vue.js Scrollable Table

I am currently working on a table that is populated using the vue.js v-for method: <table> <tr><th>Name</th><th>Surname</th></tr> <tr v-for="user in users"><td>@{{user.name}}</td><td>@{ ...

Comparing the parsing of fetch() JSON response output in Node.js to parsing a JSON variable

Could someone clarify the difference between parsing a Variable JSON object and parsing fetch() response data JSON object stored in a variable? For example: If we have a variable like this: var myJSON = { "items" : [ { "id" : &q ...

An element in AngularJS is replicated for a brief moment of 1 second

I am having trouble with my login form that displays an error message in a box. <div class="ui negative message" ng-if="vm.message != ''"> <span ng-bind="vm.message"></span> </div> The error message is being set in t ...

The div element is supposed to only be visible when the user scrolls down and then back up, rather than when the

Looking for some help with a Javascript issue on my website (http://www.pjsmusic.com). I need a div of 200px to appear when the user scrolls down 40px. I have tried using the following Javascript code: $(document).scroll(function() { $('#jerkBox& ...