JavaScript學習筆記(面向對象編程二)

Class繼承

對於js中的繼承來說,使用基於原型實現,特點是簡單缺點是理解起來特別的困難比傳統的類-實例模型要困難,最大的缺點是繼承 的實現需要編寫大題代碼,並且需要正確實現原型鏈。
用函數實現Student的方法:

function Student(name) {
    this.name = name;
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
}

class繼承

用class定義對象的另一個巨大的好處是繼承更方便了。

//使用class來寫對象
class Student {
    constructor(name){
        this.name = name;
    }
    hello(){
        console.log(`hello,${this.name}!`);
    }
}
var zs = new Student('張三');
console.log(zs.name);//張三
console.log(zs.hello());//hello,張三!
class Animal{
    constructor(name){
        this.name = name;
    }
}
class Cat{
    constructor(name){
        super(name);
    }
    say(){
        return `Hello,${this.name}!`
    }
}

var cat = new Cat('小白');
console.log(cat.name);
console.log(cat.say());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章