How to create the JavaScript class
This article mainly introduces the relevant knowledge of "how to create JavaScript class". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to create JavaScript class" can help you solve the problem.
The JavaScript class is a template for JavaScript objects
Syntax of the JavaScript class
Use the keyword class to create a class.
Always add a method named constructor ():
Grammar
Class ClassName {
Constructor () {...}
}
Example
Class Car {
Constructor (name, year) {
This.name = name
This.year = year
}
}
The above example creates a class called "Car".
The class has two initial properties: "name" and "year".
The JavaScript class is not an object.
It is just a template for the JavaScript object.
Use CLA
If you have a class, you can use it to create objects:
Example
Let myCar1 = new Car ("Ford", 2014)
Let myCar2 = new Car ("Audi", 2019)
The above example uses the Car class to create two Car objects.
The constructor method is automatically called when a new object is created.
Constructor method
The construction method is a special method:
It must have a "constructor" with the exact name
Automatically executes when a new object is created
Used to initialize object properties
If no constructor method is defined, JavaScript adds an empty constructor method.
Class method
Creation of class method
Grammar
Same as the object method.
Use the keyword class to create a class.
Always add the constructor () method.
Then add any number of methods.
Grammar
Class ClassName {
Constructor () {...}
Method_1 () {...}
Method_2 () {...}
Method_3 () {...}
}
Create a class method named "age" that returns the age of the car:
Example
Class Car {
Constructor (name, year) {
This.name = name
This.year = year
}
Age () {
Let date = new Date ()
Return date.getFullYear ()-this.year
}
}
Let myCar = new Car ("Ford", 2014)
Document.getElementById ("demo") [xss_clean] =
"My car is" + myCar.age () + "years old."
You can send parameters to class methods:
Example
Class Car {
Constructor (name, year) {
This.name = name
This.year = year
}
Age (x) {
Return x-this.year
}
}
Let date = new Date ()
Let year = date.getFullYear ()
Let myCar = new Car ("Ford", 2014)
Document.getElementById ("demo") [xss_clean] =
"My car is" + myCar.age (year) + "years old."
This is the end of the introduction to "how to create JavaScript classes". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.