Class can be used in JavaScript; a class is a function, but instead of using the keyword function for initialization, use the keyword class and assign attributes in the constructor() method, each time the class object is initialized , the constructor() method will be called, and the syntax is "class className{constructor(){...}}".
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
A class is a function, but instead of using the keyword function to initialize it, you use the keyword class and assign properties in the constructor() method.
Every time a class object is initialized, the constructor() method is called.
Note: Unlike function and other JavaScript declarations, class declarations are not hoisted (you must declare a class before you can use it).
Note: The syntax in the class must be written in "strict mode".
The syntax is:
class className { // 类主体 }
We use the class keyword to create a class. The class body is in a pair of braces {}. We can define the location of the class members in the braces {}. , such as a method or constructor.
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 example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> </head> <body> <h2>JavaScript 类</h2> <p>如何使用 JavaScript 类</p> <p id="demo"></p> <script> class Runoob { constructor(name, url) { this.name = name; this.url = url; } } let site = new Runoob("好好学习", "//m.sbmmt.com"); document.getElementById("demo").innerHTML = site.name + ":" + site.url; </script> </body> </html>
Output result:
##[Related recommendations:javascript video tutorial 、webfrontend】
The above is the detailed content of Can I use classes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!