ES6 | 类与继承

101 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

ES系列文章

//定义类class
class People {
    //构造函数
    constructor(name,age){
        this.name =name
        this.age =age
    }
    showName(){
        console.log(this.name)
    }
}
let p1 =new People('xxx',18)
console.log(p1)

在 ES6 中把类的声明专业化了,不在用 function 的方式了,而是用关键字class来声明方法,用constructor声明属性。 对比ES5可以看出,prototype上也有两个方法,也是一个是构造函数constructor,一个是自定义的方法walk,看来方法上和ES5本质上是一样的,所以得出一个结论:class 的方式是 function 方式的语法糖, 它们本质上是一样的!

继承

class People {
    constructor(name,age){
        this.name =name
        this.age =age
        this._sex = -1
    }
    //setters&&getters 
    // 属性
    //业务逻辑操作
    get sex() { 
        if (this._sex === 1) {
            return 'male'
        } else if (this._sex === 0) {
            return 'female'
        } else {
            return 'error'
        }
    }
    set sex(val) { // 1:male 0:female
        if (val === 0 || val === 1) {
            this._sex = val
        }
    }
    showName(){
        console.log(this.name)
    }
     // 静态方法 static
     //ES5中直接在类上定义静态方法
     //ES6中,用到static关键字
    static getCount() {
        return 5
    }
}
let p1 =new People('xxx',18)
console.log(p1)

// 静态属性
People.count = 9
console.log(typeof People)
// function
console.log(People.count)

//继承 extends
//ES5继承中,构造方法只能继承父类内部属性方法,不能继承原型上的属性方法,而原型链继承只能继承原型上的属性/方法,不能继承父类内部属性/方法,**所以在ES5中实现继承需要用组合式继承(构造+原型)
//在ES6中,用关键字*extends*实现继承
class Coder extends People{
     constructor(name,age,company){
        super(name,age)
        this.company =company
    }
    showCompany(){
        console.log(this.company)
    }
}
let c1 = new Coder('xxx',20,'ddd')
console.log(c1)
c1.showName()
//xxx
c1.showCompany()
//ddd
c1.sex = 1
console.log(c1.sex)
console.log(Coder.getCount())

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!