如何在 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