Reputation: 17
In a tutorial I am reading, there is a part I don't understand:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
User.prototype = {
constructor: User,
saveScore:function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd)
},
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;
}
}
I have read the post and checked the web but I don't really understand, is there a difference between saying: User.constructor and User.prototype.constructor? (Like on Line 9)
Upvotes: 0
Views: 67
Reputation: 331
When you are doing
user.prototype={},
You are actually creating new object. So it will be
user.prototype=new Object()
and its constructor will change to Object, so to keep constructor to user object
constructor: User
and constructor is property of prototype. To call constructor from class user, you need to create new instance of class user then only you can use constructor property directly
Upvotes: 1
Reputation: 16041
The User.constructor
sets the constructor of the User
instance. The User.prototype.constructor
sets the constructor of all instances. Thus if you set
User.prototype.constructor = function test(){};
then
new User().constructor
will also be the test
function.
Upvotes: 1