1. getters 與 setters
(1). 通過getters來訪問類或對象的屬性,以避免直接訪問。
- 用法:get 方法名(){ return xxx; };
如:class Aminal {
constructor (name) { this.name = name; };
get name() { return this._name; };
// get 關鍵字將Animal對象的name屬性綁定到了name()方法上,
// 這樣一來,當name屬性被訪問時,name()方法就會被調用。
};
let cat = new Animal('lulu');
console.log(cat.name); // lulu
(2). 通過setters來更改類或對象屬性的值,以避免直接更改。
- 用法:set 方法名(args) { // statements; };
如:class Aminal {
constructor (name) { this.name = name; };
get name() { return this._name; };
set name(aNewName) {
aNewName = aNewName.trim();
if (aNewName === '')
throw 'New name can't be empty';
this._name = aNewName;
};};
// set 關鍵詞將Animal對象的name屬性與name(aNewName)方法綁定,
// 這樣一來,當name屬性被賦值時,name(aNewName)方法就會被調用。
let cat = new Animal('lulu');
cat.name = 'bobo';
console.log(cat.name); // bobo
2. 類的表達式
(1). 類的表達式可以不需要在class關鍵字後面加上標識符。還可以在變量聲明中使用類表達式,並將其作爲參數傳給函數。
如:let Animal = class {
constructor(name) { this.name = name; };
get name () { return this._name };
};
let cat = new Animal('Lulu');
相當於:class Animal {
constructor(name) { this.name = name; };
get name () { return this._name };
};
let cat = new Animal('Lulu');
(2). 類表達式不能吊裝
如:let cat = new Animal('Lulu'); // 會報錯 TypeError: Animal is not a constructor
let Animal = class {
constructor(name) { this.name = name; };
get name () { return this._name };
};
(3). 類是一等公民 first-class citizen
- 我們既可以把類傳給函數,也可以從函數中返回一個類,還可以把類賦值給一個變量。
如:function aFactory (aClass) { return new aClass(); }; // 把類aClass傳給函數aFactory
let greeting = aFactory (class { hello () { console.log('Hello'); }; };);
(4). 單例 singleton
類表達式可以通過立即調用類構造函數來創建一個單例。
- 具體用法:在類表達式中使用new操作符,并在類聲明的末尾加上括號。
如:let cat = new class {
constructor(name) { this.name = name };
greeting () { console.log(`Hello, ${this.name}.`); };
} ('Lulu');
cat.greeting(); // 'Hello, Lulu.'