JavaScript class
A class is a blueprint for an object, providing a more formal and organized way to define the object and its behavior. JavaScript classes are not objects themselves, but templates for creating JavaScript objects.
The class is a special kind of function, but we use the keyword class
to define it instead of function
. Properties are assigned inside the constructor()
method.
Class method
class
keyword. constructor()
method. Example 1: Create a car class, and then create an object named "My Car" based on the car class.
<code class="language-javascript">class Car { constructor(brand) { this.carName = brand; } } let myCar = new Car("Toyota"); </code>
Constructor method
A constructor is a special method used to initialize objects created with a class. It is called automatically when a new instance of the class is created. It typically assigns values to object properties using the parameters passed to it, ensuring that the object is properly initialized when created.
When the constructor is automatically called and the class is initialized, it must have the exact name "constructor". In fact, if you don't have a constructor, JavaScript will add an invisible, empty constructor method.
Note: A class cannot have multiple constructor()
methods, which will cause a syntax error.
More class examples
<code class="language-javascript">class Person {} // 空类 class Student { constructor(rollNo, name, age) { this.name = name; this.rollNo = rollNo; this.age = age; } } let student1 = new Student(1, "Alex", 12); console.log(student1); // Output: Student { name: 'Alex', rollNo: 1, age: 12 } class Product { constructor(name, price) { this.name = name; this.price = price; } displayProduct() { console.log(`Product: ${this.name}`); console.log(`Price: ${this.price}`); } } const product1 = new Product("Shirt", 19.32); const product2 = new Product("Pant", 33.55);</code>
The above is the detailed content of Classes in javascript. For more information, please follow other related articles on the PHP Chinese website!