1. 私有字段 private fields
(1). ES2022允許在類中使用私有字段
- 使用私有字段需要在字段名前加上井號 #
如:class Animal {
#name;
constructor(name){ this.#name = name; };
get name() { return 'Hello, ' + this.#name; };
};
let cat = new Animal('lulu');
console.log(cat.name); // 'Hello, lulu'
(2). 使用getter與setter訪問私有字段
如:class Animal {
#name;
constructor(name){ this.#name = name; };
get name() { return 'Hello, ' + this.#name; };
set name(aName) {
if (aName.length > 0) { this.#name = aName }
else { throw 'New name can not be empty.'; };
};};
let cat = new Animal('lulu');
cat.name = 'bobo';
console.log(cat.name); // Hello, bobo
(3). 子類無法訪問父類的私有字段
- 私有字段僅能在申明該私有字段的類中使用。
(4). 使用 in 操作符來檢查是否存在指定的私有字段
- 用法:fieldName in objectName
如:class Animal {
#name;
constructor(name){ this.#name = name; };
get name() { return 'Hello, ' + this.#name; };
hasName(animal) {return #name in animal;};
};
let cat = new Animal('lulu');
console.log(cat.hasName(cat)); // true
(5). 靜態私有字段
如:class Animal {
#name;
static #count = 0;
constructor(name){
this.#name = name;
Animal.#count++; };
get name() { return 'Hello, ' + this.#name; };
static getCount () {return Animal.#count;};
};
let cat = new Animal('lulu');
let dog = new Animal('bobo');
console.log(Animal.getCount()); // 2