17.class

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());
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,084評論 0 9
  • 官方中文版原文鏈接 感謝社區(qū)中各位的大力支持,譯者再次奉上一點點福利:阿里云產(chǎn)品券,享受所有官網(wǎng)優(yōu)惠,并抽取幸運大...
    HetfieldJoe閱讀 2,681評論 9 22
  • 特別說明,為便于查閱,文章轉(zhuǎn)自https://github.com/getify/You-Dont-Know-JS...
    殺破狼real閱讀 726評論 0 1
  • 官方中文版原文鏈接 感謝社區(qū)中各位的大力支持,譯者再次奉上一點點福利:阿里云產(chǎn)品券,享受所有官網(wǎng)優(yōu)惠,并抽取幸運大...
    HetfieldJoe閱讀 3,726評論 2 27
  • E89 In a hastily arranged address to the American people ...
    一日一譯閱讀 249評論 0 1

友情鏈接更多精彩內(nèi)容