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

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Playlist Project

Playlist.prototype.play & Song.prototype.play: They are interacting, I'm a little foggy how.

//both Playlist and Song have a .play()
//how does Playlist distinguish which .play() to use?

Playlist.prototype.play = function(){
  var currentSong = this.songs[this.nowPlayingIndex];
  currentSong.play();
};

Song.prototype.play = function(){
  this.isPlaying = true; 
};

3 Answers

Steven Parker
Steven Parker
229,744 Points

:point_right: The method used depends on the thing you use it on.

For example, say you have a Playlist named mylist, and a Song named mysong.

Now if you do this: mylist.play(); — it will use the play method that was defined for the Playlist prototype.

But if you do this: mysong.play(); — it will use the method defined for the Song prototype.

Does that clear it up?

I have this vague idea of what you are saying. 1: are you saying it has to do with where it is called? ie: the thing you use it on? I hate to belabor this but, let me ask it this way.

//How does Playlist.prototype.play
//know that currentSong.play();
// is not referring to itself?

Playlist.prototype.play = function(){
  var currentSong = this.songs[this.nowPlayingIndex];
  currentSong.play();
};

I always appreciate your help. Thanks.

I don't know if this answer your question, but in the example of the dice was like that ( I don't know if the sintaxe it's right):

function Playlist() { this.songs = []; this.nowPlayingIndex = 0; this.currentSong = this.songs[this.nowPlayingIndex]; this.playSong = function() { this.currentSong.play(); }; }

Playlist.prototype.play it's part of Playlist, it's just outside the function.

Gislel, I took a break from js cause it was starting to make my head hurt. I'll go back to it after I finish Python. Thank you for your response, I'll keep this as reference when I need it :D

function Playlist() { 
    this.songs = []; 
    this.nowPlayingIndex = 0; 
    this.currentSong = this.songs[this.nowPlayingIndex]; 
    this.playSong = function() { 
        this.currentSong.play(); 
    }; 
}

Ok, it's dificult too learn some things in Javascript.