Gitaram Kanawade
Gitaram Kanawade

Reputation: 351

Javascript code execution sequence

    function User(firstName,EmailId){
          this.name = firstName;
          this.email = EmailId;
          this.quizScores = [];
          this.currentScore = 0;
    }
    User.prototype = {
          constructor : User,
          saveScore:function (scoreToAdd)  {
             this.quizScores.push(scoreToAdd)
          },
          showNameAndScores:function ()  {
             var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
             return this.name + " Scores: " + scores;
          },
          changeEmail:function (newEmail)  {
             this.email = newEmail;
             return "New Email Saved: " + this.email;
          }
    }

    secondUser = new User("Peter", "[email protected]");
    console.log('secondUser',secondUser);
    secondUser.changeEmail("[email protected]");
    secondUser.saveScore(18);
    secondUser.showNameAndScores();

On my console I see output as

currentScore:0
email:"[email protected]"
name:"Peter"
quizScores:[18]

Now in my above code I have created object and then immediate printed on console then I have called prototype methods still it print values updated by prototype methods.why it happens?

Before expand this object enter image description here

After Expand this object enter image description here

Upvotes: 0

Views: 54

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230276

why it happens?

console.log, when passed an object, prints a "live" object, a reference to it (at least in chrome and firefox). If you later update that object and only then expand the object in the console, you'll see the updated values. To get the current state of the object, you could print the properties individually, for example:

 console.log(secondUser.email)

Another possibility is printing a deep copy of an object, not the object itself.

Upvotes: 1

Related Questions