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 trialtal Shnitzer
Courses Plus Student 5,242 Pointswhat "this" in the following code context
function Song(title,artist,duration) {
Media.call(this,title,duration);
this.artist = artist;
}
is it Song function?
2 Answers
tal Shnitzer
Courses Plus Student 5,242 PointsI 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
Unsubscribed User
15,323 PointsThere'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.
Unsubscribed User
15,323 PointsOne more resource for you https://www.youtube.com/watch?v=GhbhD1HR5vk
tal Shnitzer
Courses Plus Student 5,242 Pointsthanks, I'll look into it
Unsubscribed User
15,323 PointsUnsubscribed User
15,323 PointsThe 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 likehello('jimmy')
you would actually have a property attached towindow
afterwards calledartist
with the value of'jimmy'
.In that case,
this
would bewindow
. Make sense?