# Classes
- (JavaScript) classes are just 'templates' for objects
- If we have only one user or one campus, object literals are just fine
- If we have 100 users or 10 campuses, object literals are not a good choice, especially if every object contains methods
- For 100 users as a template literal, we also have 100 exactly the same methodes to write!
- That's where classes come in action
# Basic class syntax
- A class always starts with the
classkeyword, followed by the class name started with a uppercase letter - Always write the name of the class in the singular form, e.g:
class User {...},class Campus {...} - In a class, the
contructormethode gets called first when creating a new instance of that class - Use the
newkeyword to instantiate (to create an object from) a class, e.g:new User {...},new Campus {...} - Open es6/class/user.html and es6/class/user.js
HTML
JavaScript
result
<pre></pre>Copied!
1
# JavaScript class vs Java class
- With a JavaScript class you do not (yet) have the same possibilities as with a real OOP-based programming language such as Java
- A brief comparison:
| description | JavaScript | Java |
|---|---|---|
| inheritance | x | x |
| getters/setters | x | x |
| static methodes | x | x |
| polymorphism | x | x |
| encapsulation | x | x |
| interfaces | - | x |
| private properties | - | x |
| private methodes | - | x |
# Example
# Campuses Thomas More Kempen
HTML
JavaScript
result
<div class="row border-green"></div>Copied!
1
# References
- Classes@Mozilla (opens new window)
- Classes@W3Schools (opens new window)

