JasonDavis
JasonDavis

Reputation: 48933

JavaScript error when reading a property within the same object?

Below is part of a larger JavaScript object in my project. I have remove a couple thousand lines of code to reveal just the part in question...

Line 6 below is the line of code in question.

Simple example of JavaScript

projectTaskModal = {

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

}

First on that line I had tried this:
$taskDueDateVal: projectTaskModal.cache.$taskDueDateSpan.dataAttr('due-date'),

but this resulted in this console error: Uncaught TypeError: Cannot read property 'cache' of undefined

Next I also tried this:
$taskDueDateVal: this.$taskDueDateSpan.dataAttr('due-date'),

but that also resulted in this console error: Uncaught TypeError: Cannot read property '$taskDueDateSpan' of undefined


As you can see on line 6 I am trying to access the value of line 5.
projectTaskModal.cache.$taskDueDateSpan

Upvotes: 1

Views: 40

Answers (2)

Pointy
Pointy

Reputation: 413720

You cannot refer to an "under construction" object from inside the object literal itself. The only thing to do us update the object after it's initially built.

projectTaskModal = {

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

};

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

Alternatively, initialize another variable with that jQuery expression, and use it for both properties:

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

projectTaskModal = {

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

}

Upvotes: 3

zerkms
zerkms

Reputation: 254916

JS is a language with strict not lazy evaluation.

Which means expressions in a statement are evaluated inside out.

projectTaskModal = {

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

}

So in this statement the right part (the object literal) is evaluated first, then a reference to it is assigned to the variable projectTaskModal.

Which means that during its evaluation the value of projectTaskModal is undefined.

Upvotes: 1

Related Questions