class 類
類的聲明
- 當使用
typeOf User的時候,得到的打印結(jié)果是function,所以類是一個特殊的函數(shù),但是函數(shù)存在函數(shù)提升,類卻沒有,所以必須在調(diào)用之前聲明。 - 只能通過
new關(guān)鍵字來調(diào)用。 - 函數(shù)名可以用計算屬性的方式定義,如:
[methodName](){ // 函數(shù)體 }。
class User {
// 構(gòu)造方法
constructor(name, email) {
this.name = name;
this.email = email;
}
// 方法之間沒有逗號分隔
info() {
console.log(`Hi,i am ${this.name},my email is ${this.email}`);
}
// 靜態(tài)方法用 `static` 來定義,只能在User對象上調(diào)用,就是原型對象調(diào)用,不能在實例上調(diào)用
static description() {
console.log(`I am a human`);
}
// `set` 方法
set github(value) {
this.githubName = value;
}
// `get` 方法
get github() {
return `https://github.com/${this.githubName}`;
}
}
const dp = new User('dp', '457509824@qq.com');
dp.info();
User.description();
dp.github = 'dptms';
console.log(dp.github);
繼承
class Animal {
constructor(name) {
this.name = name;
this.belly = [];
}
eat(food) {
this.belly.push(food);
}
}
// 通過 `extends ` 關(guān)鍵字實現(xiàn)繼承
class Dog extends Animal{
constructor(name,age){
// 通過 `super` 調(diào)用父類構(gòu)造方法
super(name);
this.age = age;
}
bark(){
console.log('bark bark!') ;
}
}
const hot = new Dog('hot',2);
拓展內(nèi)建對象數(shù)組
在 ES6 之前,我們很難在內(nèi)建對象的基礎(chǔ)上擴建自己的類。 ES6 的 Class 采用了另一種機制來解決這個問題。
class MovieCollection extends Array {
constructor(name, ...items) {
super(...items);
this.name = name;
}
add(movie) {
this.push(movie);
}
topRated(limit = 3) {
return this.sort((a, b) => a.score < b.score).slice(0, limit);
}
}
const movies = new MovieCollection('favorite movies',
{ name: 'The Croods', score: 8.7 },
{ name: 'The Shawshank Redemption', score: 9.6 },
{ name: 'Leon', score: 9.3 },
{ name: 'Days of summer', score: 8.0 },
);
movies.push({ name: '功夫熊貓', score: 9.7 })
console.log(movies.topRated());