0

I'm learning JS but am confused about the below's part of Song.prototype = Object.create(Media.prototype); and Movie.prototype = Object.create(Media.prototype); parts. Why are they needed if the Media function is within scope?

function Media(title, duration) {
  this.title = title;
  this.duration = duration;
  this.isPlaying = false;
}


Media.prototype.start = function start() {
  this.isPlaying = true;
};

Media.prototype.stop = function stop() {
  this.isPlaying = false;
};

function Song(title, artist, duration) {
  Media.call(this, title, duration);
  this.artist = artist;
}

Song.prototype = Object.create(Media.prototype);

function Movie(title, year, duration) {
  Media.call(this, title, duration);
  this.year = year;
}

Movie.prototype = Object.create(Media.prototype);
mangocaptain
  • 1,435
  • 1
  • 19
  • 31
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create – ryanlutgen Aug 10 '16 at 00:22
  • Prototypal inheritance isn't related to scope. It instead creates a chain of objects that get used when looking up a property. So you look for a property on your object, and it isn't there, it gets checked on the next object in the chain. Not there? It goes to the next object, and so on until `null` is reached. Often the chain is only a couple objects long. –  Aug 10 '16 at 00:35
  • @squint but why does this have to go through the prototype or inheritance at all? doesn't Movie or Song already have access to the Media call because it's in the the larger scope? – mangocaptain Aug 10 '16 at 01:58
  • 1
    Yes, it has access to `Media` and therefore `Media.prototype`. So if you really wanted, you could take a `movie` that you created, and do `Media.prototype.start.call(movie)` instead of doing `movie.start()`, assuming that your `movie` object also is in the same scope, which it may not be. I think `movie.start()` is nicer. –  Aug 10 '16 at 13:07

0 Answers0