Classes
JavaScript uses the prototypal inheritance model: each object inherits the fields (properties) and methods of the prototype object.
class
The keyword class
is used to define a class:
class MyClass {
// class methods
constructor() { ... }
method1() { ... }
method2() { ... }
method3() { ... }
...
}
This syntax is called a class declaration.
Class syntax differs from object literals. No commas are required inside classes.
The class may not have a name. A class expression can be used to assign a class to a variable :
const UserClass = class {
// class body
}
Classes can be exported as modules. Here's an example of the default export:
export default class User {
// class body
}
And here's an example of a named export:
export class User {
// class body
}
The class becomes useful when you instantiate the class. An instance is an object that contains the data and behavior described by class.
The new
operator creates an instance of a class in JavaScript like this: instance = new Class()
.
For example, you can create an instance of the User class👤 using the new
operator:
const myUser = new User()
new User()
creates an instance of the User
class 👤.
Initialization: constructor ()
constructor (...)
is a special method in the body of the class that initializes an instance. This is the place where you can set initial values for the fields or make any adjustments to the objects.
In the following example, the constructor sets the initial value of the name
field:
class User {
constructor(name) {
this.name = name
}
}
The constructor
of the User
class takes one parameter, name
, which is used to set the initial value of the this.name
field.
Inside the constructor, the value of this
is equal to the newly created instance.
The arguments used to instantiate the class become parameters to the constructor :
The name
parameter inside the constructor is Jon Snow
.
If you do not define a constructor for a class, a default constructor is created. The default constructor is an empty function⚙️ that does not modify the instance.
There can be only one method named constructor
in a class.
Discarding classes
Since in the course of our school we teach to develop mobile applications using the library React, where is the innovation React Hooks allows you to use state and other React features without writing classes. Therefore, it makes no sense to talk about classes anymore, since we have abandoned them.
Problems?
Write to Discord chat.
Questions:
What is the keyword for class definition?
constructor()
class
this
Are methods inside a class comma separated?
- Yes
- No
How many constructor()
methods can there be in one class?
- Unlimited
- Up to ten
- Only one
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Links:
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Philipp Dvinyaninov | Dmitriy Vasilev 💵 | Resoner2005 🐛 🎨 🖋 | Navernoss 🖋 🐛 🎨 |