0

    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

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Sergio.Its helpful
@GitaramKanawade: JFYI, you're expected to accept helpful answers. (the green checkmark on the left)
@GitaramKanawade: you should also go through your past questions and upvote/accept where appropriate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.