如何在 JavaScript 中使用静态变量?
关键字“Static”用于定义类的静态方法或静态属性。静态方法的好处在于我们不需要创建类的实例或对象。它没有多个值。它将在初始化期间定义一个静态值。
关键字static类似于const关键字。它在初始化发生时的运行时被设置,这些类型的变量具有全局存在性和作用域。我们可以在脚本的任何地方使用这些静态变量。
注意 - 与const变量不同,我们可以重新分配和更改static变量的值。
示例 1
在这个示例中,我们正在创建一个简单的 HTML 页面。我们添加了一个包含示例类的脚本。该类包含在运行时初始化的静态值,因此之后在代码中使用该值。
# index.html
<!DOCTYPE html>
<html>
<head>
<title>Static Variables</title>
</head>
<body>
<h1 style="color: red;">
Welcome To Tutorials Point
</h1>
<script type="text/javascript">
class Example {
static staticVariable = 'Welcome To Tutorials Point';
// Defining the Static Variables
static staticMethod() {
return 'I am a static method.';
}
}
// Calling the Static Variables
console.log(Example.staticVariable);
console.log(Example.staticMethod());
</script>
</body>
</html>输出
它将在控制台中产生以下输出。
Welcome To Tutorials Point I am a static method.
示例 2
# index.html
<!DOCTYPE html>
<html>
<head>
<title>Static Variables</title>
</head>
<body>
<h1 style="color: red;">
Welcome To Tutorials Point
</h1>
<script type="text/javascript">
class Example {
static staticVariable = 'Welcome To Tutorials Point';
// Defining the Variable under a Static Method
static staticMethod() {
return 'staticVariable : '+this.staticVariable;
}
}
// Calling the above static method
console.log(Example.staticMethod());
</script>
</body>
</html>输出
在成功执行上述程序后,它将在控制台中产生以下输出。
staticVariable : Welcome To Tutorials Point
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP