Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Adiv Abramson
6,919 PointsIf the prototype relies on external functions won't external function variables be overwritten with each new object?
If I understood the lesson so far, we place functions for prototypes in external code blocks and then assign them to constructor functions via the prototype property, e.g.
//constructor function for Song objects
function Song(title, artist, duration) {
this.title = title;
this.artist = artist;
this.duration = duration;
this.playCount = 0;
}//Song
//in order to avoid multiple copies of the same code in memory
//assign external function to constructor function via its
//prototype property:
Song.prototype.play = function() {
console.log("Now playing " + this.title + " by " + this.artist + ".");
this.playCount++;
}
var song1 = new Song("Live And Let Die", "Wings", "3;53");
var song2 = new Song("Jump!", "Van Halen", "3:25");
song1.play();
song2.play();
song1.play();
song2.play();
Will playCount be incremented properly for each song object? Since there is only one copy of the code in memory, is the this property overwritten each time? Thank you
Ricky Walker
12,863 PointsRicky Walker
12,863 PointsHi Adiv,
What the constructor does in this example is create new instances for the Song class. playCount will be incremented properly for each song object like you initially assumed. Every time you create a new instance, like with song1 and song2, playCount begins at 0. Once the play method is called, it is only incremented for whatever instance called the play method.