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", "Peter@examnple.com");
console.log('secondUser',secondUser);
secondUser.changeEmail("Richard@examnple.com");
secondUser.saveScore(18);
secondUser.showNameAndScores();
在我的控制台上,我看到输出为
currentScore:0
email:"Richard@examnple.com"
name:"Peter"
quizScores:[18]
现在,在上面的代码中,我创建了对象,然后立即在控制台上打印,然后我调用了原型(prototype)方法,但它仍然打印由原型(prototype)方法更新的值。为什么会发生这种情况?
最佳答案
why it happens?
console.log
,当传递一个对象时,打印一个“事件”对象,一个对其的引用(至少在 chrome 和 firefox 中)。如果您稍后更新该对象,并且仅然后在控制台中展开该对象,您就会看到更新的值。要获取对象的当前状态,您可以单独打印属性,例如:
console.log(secondUser.email)
另一种可能性是打印对象的深拷贝,而不是对象本身。
关于Javascript代码执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403237/