Home > Web Front-end > Front-end Q&A > Can I use classes in JavaScript?

Can I use classes in JavaScript?

WBOY
Release: 2022-10-20 14:03:41
Original
2355 people have browsed it

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(){...}}".

Can I use classes in JavaScript?

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

Class can be used in JavaScript

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 {
  // 类主体
}
Copy after login

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>
Copy after login

Output result:

Can I use classes in JavaScript?

##[Related recommendations:

javascript video tutorialwebfrontend

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template