JavaScript 自學筆記21

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.'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值