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) Prototypal Inheritance Updating the Song Object

lokesh cherukuri
lokesh cherukuri
381 Points

Cant we copy prototype by Song.prototype = Media.prototype

Cant we copy prototype by Song.prototype = Media.prototype; instead of Song.prototype = Object.create(Media.prototype)

1 Answer

Joel Kraft
STAFF
Joel Kraft
Treehouse Guest Teacher

Hi lokesh cherukuri,

We want Song's prototype object to inherit functionality from Media's prototype object. In other words, we want any object that Song produces (using the new keyword) to be able to use methods on both Song.prototype and Media.prototype.

However, we don't want to put any methods that should belong to Song.prototype on Media.prototype, or write over any of Media.prototype's methods when setting up Song.prototype.

Setting

Song.prototype = Media.prototype

means that both would share the exact same object, meaning that any changes made to Song.prototype would show up on Media.prototype.

By setting

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

we get a fresh, blank object that still inherits from Media.prototype. So now changes made to Song.prototype won't pollute Media.prototype, but any changes made to Media.prototype can be accessed by song instances.

Does that make sense?

Live Kigozi
Live Kigozi
3,014 Points

Thanks Joel. That explanation was so clear it answered a lot of my questions. OOP can get one confused even in strictly typed languages. That explanation really cut it for me tho.

Thanks again.