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!
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
Zijun Liao13,409 Points
I notice that sometimes people use function keyword to declare a class like the second example, and sometimes use class.
Are there any different, and when I should use class or function?
Alex KoumparosPython Development Techdegree Student 36,886 Points
class is syntactic sugar introduced in ECMAScript 2015 (aka ECMAScript 6). It is intended to provide a way for developers who are familiar with class-based OO to work more efficiently with JS's prototype-based OO.
If you are already familiar with languages like Java, C++, Python, etc, the
class keyword you are creating exactly the same kind of object as you would using the older syntax. This can cause unpleasant surprises for people expecting the 'class' objects to work just like in other languages. All the peculiarities of JS's prototype-based object model are still present. The most fundamental point being that in true class-based OO languages, instantiation of an object is a copy action: the original class is not subject to modification by the instance. However, in JS, when you create an object from another object (even if that other object was defined using the
class keyword) you are not making an independent instance, you are making a delegation link between the prototype object and the new object. This means that there are circumstances where modifications to your new object can change the 'parent' object.
class syntax works behind the scenes. All of which can be read online for free.
When writing your own code, use whichever way you prefer, but you're going to keep running into other people's code written both ways, so you'll have to get comfortable with both approaches.
Hope that helps.
Class is the newer simpler syntax.