Class is a blueprint for creating object templates in JavaScript. It defines the properties and methods of an object, which are accessed by creating an instance using the new keyword. Advantages of Class include better code organization, increased readability and maintainability, and simplified object creation. A Class can add properties through constructors, define methods through functions, and extend other Classes to inherit their properties and methods using the extends keyword.
Usage of Class in JavaScript
What is Class?
Class is a blueprint in JavaScript that is used to create instances of objects. It defines the properties and methods of the object and acts as a template.
Create Class
Use the keywordclass
to create a Class, followed by the Class name:
class MyClass { // 代码 }
Add attributes
Add properties by assigning values in the constructor:
class MyClass { constructor(name, age) { this.name = name; this.age = age; } }
Add methods
Use functions in Class to define methods:
class MyClass { constructor(name, age) { this.name = name; this.age = age; } speak() { console.log(`My name is ${this.name} and I am ${this.age} years old.`); } }
Create an object instance
Use thenew
keyword to create a Class instance:
const myObject = new MyClass('John', 30);
Access properties and methods
Access the properties of the object through dot syntax and methods:
console.log(myObject.name); // 'John' myObject.speak(); // 输出 "My name is John and I am 30 years old."
Expand Class
Use theextends
keyword to extend other Classes and inherit their properties and methods:
class SubClass extends MyClass { constructor(name, age, hobby) { super(name, age); this.hobby = hobby; } }
Advantages
The advantages of using Class include:
The above is the detailed content of Usage of class in js. For more information, please follow other related articles on the PHP Chinese website!