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 trialKashish Singal
3,368 PointsWhen to use "this" in the function and when to use prototypes
Hi guys I am confused about why this.(property) is used in the function and why other times there is a prototype built for it. Why aren't there just prototypes built for each property? And also to stop the current playing song, currentSong.stop() is used in one prototype and this.stop() is used in the other, why?
2 Answers
Adam Bowers
11,812 PointsHey Kashish,
I wondered this myself for a while too. But actually is pretty logical.
When you use a constructor function to create an object with properties and methods...For example.
var Lamp = function (bulb, state){
this.bulb = bulb;
this.ison = state;
this.pressSwitch = function (){
If (this.ison){
this.ison = false;
}
else{
this.ison = true;
}
};
};
var bedroomLight = new Lamp ('LED' false );
Each time you create a new object it will have its own copy of the Lamp.pressSwitch method.
This is pointless because all lamps perform the same task. So instead of having objects repeat themselves and use memory. You can create a prototype method instead. So every time you call new Lamp the object created Inherits the function rather than having its own copy of the same code.
This is my understanding. Hope it helps.
Lukas Smith
4,026 PointsTry imagine you have a House and You have in THIS house light switch. When you project the HOUSE and write HOUSE include SWITCH LIGHT always when you are in THIS house U can use the THIS.switch You don't need to tell anyone: I AM USING my HOUSE.SWITCH to LIGHT. U can tell I am using THIS.switch because U are in HOUSE. If U are in function U can use this.(property)
Kashish Singal
3,368 PointsKashish Singal
3,368 PointsSo how do you know when to use prototypes and when to just assign a property a function in the object? Also, in the video, why is this.stop() used rather than currentSong.stop() in different places of code when they both basically reference the same thing?