3

I want to assign property age to the object and I know it can be done using a function like:

var john = {
         firstName: "John",
         lastName: "Smith",
         job: "Teacher",
         yearOfBirth: 1990,
         family: ['Jane', 'Mark', 'Bob'],
         calculateAge: function() {
            this.age = 2018 - this.yearOfBirth
         }
      }             

   john.calculateAge();

It adds property age into the object John as expected. But can it be done without a function?

When I tried to do like following:

var john = {
             firstName: "John",
             lastName: "Smith",
             job: "Teacher",
             yearOfBirth: 1990,
             family: ['Jane', 'Mark', 'Bob'],
             age: 2018 - this.yearOfBirth
          }

"age" property returns "NaN". I don't know why it is not returning a number. Is it regular behavior (if 'yes', then why?) or am I doing something wrong over here?

Gourav Pokharkar
  • 1,568
  • 1
  • 11
  • 33

3 Answers3

1

You cannot get any value from an object that has not been finished being declared yet. At the time you write age: 2018 - this.yearOfBirth, var john is not defined (and even if it was, the calling context would be suspect - might be the global object, might be undefined).

Assign the age property after the initial object declaration instead.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

In the case of:

calculateAge: function() {
 this.age = 2018 - this.yearOfBirth
}

john.calculateAge();

the this referes to john because calculateAge is called on john

For the first code:

age: 2018 - this.yearOfBirth

this refers to the current context in which you create the john object.

You would need to write it that way:

var john = {
   firstName: "John",
   lastName: "Smith",
   job: "Teacher",
   yearOfBirth: 1990,
   family: ['Jane', 'Mark', 'Bob']
} 

john.age = 2018 - john.yearOfBirth
t.niese
  • 39,256
  • 9
  • 74
  • 101
1

On :

var john = {
             firstName: "John",
             lastName: "Smith",
             job: "Teacher",
             yearOfBirth: 1990,
             family: ['Jane', 'Mark', 'Bob'],
             age: 2018 - this.yearOfBirth
          }

this isn't refering to your object at this position and john isn't yet declared.

You can use this approach below to define age attribute when john exists :

var john = {
             firstName: "John",
             lastName: "Smith",
             job: "Teacher",
             yearOfBirth: 1990,
             family: ['Jane', 'Mark', 'Bob'],
          };        
          john.age = 2018 - john.yearOfBirth;
          
          console.log(john.age);
Sébastien S.
  • 1,444
  • 8
  • 14