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

tal Shnitzer
PLUS
tal Shnitzer
Courses Plus Student 5,242 Points

what "this" in the following code context

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

is it Song function?

The this context is probably whatever class it's in. You can't tell what "this" is without a little more context.

If you were to paste function hello(artist) {this.artist = artist} into your browser and call it like hello('jimmy') you would actually have a property attached to window afterwards called artist with the value of 'jimmy'.

In that case, this would be window. Make sense?

2 Answers

tal Shnitzer
PLUS
tal Shnitzer
Courses Plus Student 5,242 Points

I understand your answer. but it is more confusing now than it was before. in the example I gave, "this" should be Song function, which is passed to Media function which is a constructor function that adds properties. it should not be window object

There's a really good article here on how it works. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Moral of the story, functions are flexible and can be used a lot of different ways. In general, my preference is to explicitly declare the input and output of a function so all the the this magic goes away.

You do end up working with it some in both Angular and a lot in React so I would pay attention to it. Again though, to me it's an pattern to use only when you have to.