Home > Article > Web Front-end > Are there classes in javascript?
There are classes in javascript. A class is a template used to create objects. Classes in JS are built on prototypes; starting from ES6, JavaScript can use the class keyword to declare a class, with the syntax "class ClassName{constructor(){...}}".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
There are classes in javascript.
Classes are templates used to create objects. They encapsulate the data in code to process that data. Classes in JS are built on prototypes, but also have certain syntax and semantics not shared with ES5 classes.
Class declaration
We use the class keyword to create a class. The class body is in a pair of braces {}. We can define it in the braces {}. The location of class members, such as methods or constructors.
Each class contains a special method constructor(), which is the constructor of the class. This method is used to create and initialize an object created by class.
The syntax format for creating a class is as follows:
class ClassName { constructor() { ... } }
The class keyword of ES6 is actually just a syntactic sugar, and it still relies on the prototype (prototype) mechanism internally.
Example:
class phpCN { constructor(name, url) { this.name = name; this.url = url; } }
The above example creates a class named "phpCN".
Two attributes are initialized in the class: "name" and "url".
Using classes
After defining the class, we can use the new keyword to create objects:
class phpCN { constructor(name, url) { this.name = name; this.url = url; } } let site = new phpCN("php中文网", "https://www.php.cn");
The constructor will be automatically called when creating an object Function method constructor().
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of Are there classes in javascript?. For more information, please follow other related articles on the PHP Chinese website!