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 trialDávid Molnár
27,081 Points[JavaScript] get vs simple function
Hello everyone
I wonder if there's any difference between get and a simple function like:
class Example () {
constructor() {}
get activity() {
return "sleeping";
}
isEating() {
return true;
}
}
Both are very simple but I think it is enough to show my concern. As I see in the curses both can be used to return a value no matter if it's more complicated or not. Same goes for "set". I am sure there's a good reason why get / set exists in JavaScript, could you explain me please? Or it's simply because they can have the same name?
3 Answers
Steven Parker
231,248 PointsThe main difference between getters and other methods is how they are accessed. Methods are called by adding parentheses after their names and can take arguments, but getters are called just by naming them (and can't have arguments). So in usage, getters seem to be more like properties than methods.
For examples, using your class (after removing the parentheses from the class definition line):
instanceOfExample = new Example();
let eating = instanceOfExample.isEating(); // the function is invoked using parentheses
let status = instanceOfExample.activity; // the getter is invoked just by naming it
bobdeei
8,575 PointsHi Steven, I understand what you mean in the code. But I have another concern that seems to be like David's. What's the real application or the real reason behind the get function? We won't see the get function if you log the object because it's not attached to the object, but how does this benefit our code?
Steven Parker
231,248 PointsIt allows you to create a "computed property" where some code is necessary to return the value. This allows you to have the data represented by a property and reserve methods for things that cause changes.
Van Tran Huu
16,694 Pointsthe get method seems working like a computed property than a method. A computed property is a 'dynamic' property (data) which is computed based on some fixed properties, I suppose!
olu adesina
23,007 Pointsolu adesina
23,007 Pointsthanks Steven this explanation makes perfect sense
Kirt Perez
7,374 PointsKirt Perez
7,374 PointsWhat is the advantage of this though? Removing just a parentheses?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsEssentially, yes, but it's more about the conceptual aspect of having it behave like a property instead of a method.