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 trialliam johnshon
Courses Plus Student 904 Points.add ()?
what is .add() here why we're using this ?
playlist.add(song);
2 Answers
Adrian Patrascu
15,279 PointsHi Liam,
.add() is a method of the playlist application Andrew is showing and it basically adds the song to the playlist. If you do not use that method the playlist will not have the information about the song you want to use in it.
I hope this helps!
Thank you, Adrian
Ikuyasu Usui
36 PointsWe have created .add() in playlist.js as a method to the prototype of Playlist:
function Playlist() { ... }
Playlist.prototype.add = function(song) {
this.songs.push(song);
};
We could have created .add() as a method to the Playlist constructor and it would work totally fine like this:
Playlist.add = function(song) {
this.songs.push(song);
};
But, if you do that objects created from Playlist by issuing "new" will have its own memory allocated to store .add() method while those objects essentially use the exact same method.
One way to resolve this is to create add() function that can be assessed globally and let Playlist refer to this function
for the .add() method:
function add(song) {
this.songs.push(song);
}
function Playlist() {
this.songs = [];
this.nowPlayingIndex = 0;
this.add = add;
}
But then the add() function is not meant to be used by other than a Playlist object, so you contain it within the context of Playlist by putting it as a method of Playlist prototype.