0
点赞
收藏
分享

微信扫一扫

【ES6 教程】第四章 ES6类05—如何定义一个类的所有实例

【ES6 教程】第四章 ES6类05—如何定义一个类的所有实例_javascript

英文 | https://www.javascripttutorial.net

翻译 | 杨小爱


在今天的教程中,我们将一起来学习 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 静态属性增加一:

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 访问构造函数中的静态属性。




【ES6 教程】第四章 ES6类05—如何定义一个类的所有实例_构造函数_02

【ES6 教程】第四章 ES6类05—如何定义一个类的所有实例_javascript_03

举报

相关推荐

0 条评论