2

I have the following JS Code:-

var Person = function(name, yob, job) {
    this.name = name;
    this.yearOfBirth = yob;
    this.job = job;
    this.calculateAge = function() {
        this.age = 2020 - this.yearOfBirth;
    };
};

var john = new Person("John Wick", 1990, "Assasin");
console.log(john);
john.calculateAge();

Running the file gives me the following Output:- OutPut

My Question is if I called the calculateAge() function after logging the Object. How did the logged Output Object get the "age" property. As JS is a scripting Language, The statements are executed in order so technically the logged John Wick object should not have the age property but it is not following the expected behaviour. Where am I going wrong??

Pierre
  • 643
  • 1
  • 7
  • 14
  • 2
    When it was printed, it didn't have it. When you expanded it, it was updated. – Angel Politis Apr 02 '20 at 18:31
  • 1
    That's probably just a timing issue with the console. Since what was logged was a *reference* to your object, when you then went to view it in the console, it had been updated. To be sure, you could log a `JSON.stringify`ed version of it. – Scott Sauyet Apr 02 '20 at 18:31
  • 2
    If you want to see the state of an Object at any given time during the execution of your code, you could `console.log(JSON.stringify(obj, 0, 2));` – blex Apr 02 '20 at 18:34
  • by the way, read the `function-constructor` tag description, this has nothing to do here – Pierre Apr 02 '20 at 18:34

0 Answers0