constructor and instance
Learn to create a new instance with constructor and the new operator.
What is a constructor?
A constructor is a special method that runs when a new instance is created from a class. Its name is always constructor, and it usually sets the initial properties of the instance.
class User {
constructor(name) {
this.name = name;
}
}Here this points to the new instance, and this.name adds a property to it.
The new operator
To create an instance you use the new operator: const u = new User("Alex");. This expression does the following:
- Creates a new empty object.
- Calls the
constructorand bindsthisto that object. - Returns the created object.
The result, assigned to u, is an instance of the class.
Exercise Product class
Declare a Product class. Its constructor takes name and price parameters and assigns them to this.name and this.price.
Show example solution
Inside the constructor write this.name = name and this.price = price.
Example solution:
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
Test yourself
-
What does `new User("Alex")` return?
new User("Alex")- a class
- a method
- a property
- an instance
Show answer
an instance — Correct! The new operator returns a new instance of the class.
-
Create a new instance
const u = ____;Show answer
const u = new User(); -
Match the concepts
- constructor
- initializer method
- new
- instance creation operator
- this
- points to the new instance
- instance
- object made from a class