![](/style/images/good.png)
![](/style/images/bad.png)
JavaScript 静态属性
source link: https://www.myfreax.com/javascript-static-properties/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
![JavaScript 静态属性](https://www.myfreax.com/content/images/2023/04/javascript-static-properties.webp)
JavaScript 静态属性
在本教程中,您将了解 JavaScript 类的静态属性以及如何在静态方法、类构造函数和其他实例方法访问静态属性。
JavaScript 静态属性介绍
与静态方法一样,静态属性由类的所有实例共享。要定义静态属性,您可以使用static
关键词后跟属性名称,如下所示:
class Item {
static count = 0;
}
要访问静态属性,您可以使用类名称后跟 .
运算符和静态属性名称。例如:
console.log(Item.count); // 0
要在静态方法中访问静态属性,可以使用类名后跟运算 .
符和静态属性名。例如:
class Item {
static count = 0;
static getCount() {
return Item.count;
}
}
console.log(Item.getCount()); // 0
要在类构造函数或实例方法中访问静态属性,请使用以下语法:
className.staticPropertyName;
this.constructor.staticPropertyName;
下面的示例在类构造函数增加静态属性 count
:
class Item {
constructor(name, quantity) {
this.name = name;
this.quantity = quantity;
this.constructor.count++;
}
static count = 0;
static getCount() {
return Item.count;
}
}
当您创建 Item
类的实例时,以下语句将静态属性 count
增加 1:
this.constructor.count++;
// Item class ...
let pen = new Item("Pen", 5);
let notebook = new Item("notebook", 10);
console.log(Item.getCount()); // 2
此示例创建 Item
类的两个实例,它们都会调用类的构造函数。由于每次调用类的构造函数时都会将 count
属性增加 1,因此 count
的值是 2。
把它们放在一起,就是下面这样。
class Item {
constructor(name, quantity) {
this.name = name;
this.quantity = quantity;
this.constructor.count++;
}
static count = 0;
static getCount() {
return Item.count;
}
}
let pen = new Item('Pen', 5);
let notebook = new Item('notebook', 10);
console.log(Item.getCount()); // 2
- 类的静态属性由类的所有实例共享。
- 使用
static
关键字定义静态属性。 - 使用
className.staticPropertyName
在静态方法访问静态属性。 - 使用
this.constructor.staticPropertyName
或className.staticPropertyName
构造函数访问静态属性。
微信公众号
支付宝打赏
![myfreax 淘宝打赏](https://www.myfreax.com/assets/images/taobao.webp)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK