ES之類和繼承

原型繼承
function User(name,age) {
    this.name=name
    this.age=age
}

User.prototype.info=function(){
    console.log(`my name is ${this.name}`)
}
const u1=new User('hk',22);

類的聲明

靜態方法只能類本身來調用

類的聲明必須在使用之前,不像函數式的聲明

class User{
    
}
或者
const User=class {
    
}
class User{
    constructor(name,age){
        this.name=name
        this.age=age
    }
    info(){
        console.log(`hello ${this.name}`)
    }
    static desc(){
        console.log("version 11")
    }
    set github(value){
        this.name=value
    }
    get github(){
        return `https://github.com/${this.name}`;
    }
}
const tom=new User("tom","20")
tom.github='tom'

extends

class Animal{
    constructor(name){
        this.name=name;
        this.belly=[];
    }
    eat(food){
        this.belly.push(food)
    }
    speak(){
        console.log(`I am ${this.name}`)
    }
}
class Dog extends Animal{
    constructor(name,age){
        super(name)
        this.age=age
    }
    bark(){
        console.log("bark bark!")
    }
    speak(){
        console.log(`bark bark I am ${this.name}`)
    }
}

const d1=new Dog('hk',18)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章