How can I resolve a JavaScript issue that occurs when accessing a property within the same object?

Displayed below is a snippet from a much larger JavaScript object within my project. Thousands of lines have been omitted to focus solely on the area in question...

Line 6 is specifically where the issue lies.

Here's a concise example involving JavaScript:

projectTaskModal = {

    // Storing Cached Properties
    cache: {
        $taskDueDateSpan: $('#task-modal-due-date-span'),
        $taskDueDateVal: projectTaskModal.cache.$taskDueDateSpan.dataAttr('due-date'),
    }

}

Initially, I attempted the following:

$taskDueDateVal: projectTaskModal.cache.$taskDueDateSpan.dataAttr('due-date'),

This led to the console displaying the error message:

Uncaught TypeError: Cannot read property 'cache' of undefined

Subsequently, I also tried:

$taskDueDateVal: this.$taskDueDateSpan.dataAttr('due-date'),

However, this resulted in another console error:

Uncaught TypeError: Cannot read property '$taskDueDateSpan' of undefined


Upon examining line 6, it's evident that I am attempting to retrieve the value from line 5.

projectTaskModal.cache.$taskDueDateSpan

Answer №1

When working with an object literal, it is not possible to reference an "under construction" object from within the same object itself. The best approach is to update the object once it has been fully built.

projectTaskModal = {

    // Cache Properties
    cache: {
        $taskDueDateSpan: $('#task-modal-due-date-span')
    }

};

projectTaskModal.cache.$taskDueDateVal = projectTaskModal.cache.$taskDueDateSpan.dataAttr('due-date');

Another option is to initialize a separate variable with the jQuery expression and then use this variable for both properties:

var $dueDateSpan = $('#task-modal-due-date-span');

projectTaskModal = {

    // Cache Properties
    cache: {
        $taskDueDateSpan: $dueDateSpan,
        $taskDueDateVal: $dueDateSpan.dataAttr('due-date')
    }

}

Answer №2

JavaScript is known for its strict approach to evaluation, ensuring no laziness.

This means that expressions within a statement are evaluated from the inside out.

projectTaskModal = {

    // Caching Properties
    cache: {
        $taskDueDateSpan: $('#task-modal-due-date-span'),
        $taskDueDateVal: projectTaskModal.cache.$taskDueDateSpan.dataAttr('due-date'),
    }

}

Therefore, in this scenario, the object literal on the right side is evaluated before being assigned to the variable projectTaskModal.

As a result, the value of projectTaskModal remains undefined during this evaluation process.

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

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Loading remote content on a server for my Firefox OS application - On the Web and FxOS device

I haven't come across this issue in any forum, so I decided to reach out here. I'm encountering a problem with my FirefoxOS app on my FirefoxOS device (Geeksphone Developer Preview) when trying to retrieve remote content from the server. I am m ...

Updating a radio button's value with JQuery: A step-by-step tutorial

I've encountered an issue with my HTML code for radios: <input type='radio' name='a_27' value='Yes' id='a_27_0' /> <input type='radio' name='a_27' value='No' id='a_2 ...

Using JQUERY to handle event bubbling in the DOM after an AJAX call

I have been attempting to dynamically append content to a specific div using .ajax() and then utilize the new content within a jQuery Dialog. I believe that my usage of .on() is correct, but it appears that the DOM is not being properly updated. Here is t ...

The use of async components in Vue.js with named imports

I understand how to dynamically load components asynchronously in Vue. For example, instead of importing MyComponent directly: import MyComponent from '@/components/MyComponent' export default { components: { MyComponent } } We can use ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

Vue.js Class-based Decorator not Transmitting Event from Child to Parent Component

I'm fairly new to working with Vue.js and I've encountered an issue with the child to parent emit functionality. Essentially, I have a Box component that contains a Search component. In the Search component, I attempted the following: @Watch("se ...

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

How does the keyof operator fetch non-enumerable inherited properties from an object literal type?

Take a look at this TypeScript code: 'use strict'; type Value = 1 | 2 ; type Owner = 'ownerA' | 'ownerB'; type ItemType = 'itemTypeA' | 'itemTypeB'; type Item = { type: ItemType; owner: Owner; value: ...

Efficiently transferring time values from dynamically created list items to an input box using JavaScript

Is there a way to store a dynamically generated time value from an li element into an input box using JavaScript? I have a basic timer functionality on my website that includes starting, stopping, pausing, taking time snaps, and resetting them. These time ...

JavaScript Method for Retrieving Form Element Values

I am currently working on retrieving the value of an input element in a popup window that is launched from a parent page. Here is my code, but I am facing difficulties in obtaining the pc value from the input field. <html> <head> <? $pid= ...

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

Can you verify the standard behavior when importing index.js using create-react-app?

I'm trying to wrap my head around why, when using create react app, if a folder contains an index.js file and you want to import it, you only need to specify the folder name. I've been wondering where this default behavior is configured to autom ...

ReactJS encountered an error: _this3.onDismissID is not defined as a function

My goal is to retrieve the latest news related to a specific search term from a website, showcase them, and provide a dismiss button next to each news item for users to easily remove them if desired. Here's a snippet of the code I'm using: import ...

Executing a JQuery click event without triggering a page refresh

I'm dealing with a basic form on a webpage <div class="data-form"> <p>Are you hungry?</p> <form> <label class="radio-inline"><input type="radio" name="optradio" value="yes">Yes</label> ...