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 keyword class
to create a Class, followed by the Class name:
<code>class MyClass { // 代码 }</code>
Add attributes
Add properties by assigning values in the constructor:
<code>class MyClass { constructor(name, age) { this.name = name; this.age = age; } }</code>
Add methods
Use functions in Class to define methods:
<code>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.`); } }</code>
Create an object instance
Use the new
keyword to create a Class instance:
<code>const myObject = new MyClass('John', 30);</code>
Access properties and methods
Access the properties of the object through dot syntax and methods:
<code>console.log(myObject.name); // 'John' myObject.speak(); // 输出 "My name is John and I am 30 years old."</code>
Expand Class
Use the extends
keyword to extend other Classes and inherit their properties and methods:
<code>class SubClass extends MyClass { constructor(name, age, hobby) { super(name, age); this.hobby = hobby; } }</code>
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!