ECMAScript-es6中的类和继承

一、es6中的类和继承
1. 类的定义和继承,关键字class、extends、constructor、super
class People {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    showName() {
        console.log(this.name);
    }
}

let p = new People('zhangsan', 18)
console.log(p)

// 子类
class Coder extends People {
    constructor(name, age, company) {
        // 调用父类的属性
        super(name, age)
        this.company = company
    }

    showCompany(){
        console.log(this.company)
    }
}

let c = new Coder('lisi', 38, 'alibaba')
c.showName() //  lisi
c.showCompany() // alibaba
2. 定义属性,这边注意设置死循环。【set/get】
class People {
    constructor(name, age) {
        this.name = name
        this.age = age
        this._sex = -1 
    }

    get sex() {
        return this._sex
    }

    set sex(val){
        this._sex = val // 这边为什么使用_sex,原因:如果使用sex,那this.sex会再次调用set方法,产生死循环。
    }

    showName() {
        console.log(this.name);
    }
}

let p = new People('zhangsan', 18)
console.log(p)

// 子类
class Coder extends People {
    constructor(name, age, company) {
        // 调用父类的属性
        super(name, age)
        this.company = company
    }

    showCompany(){
        console.log(this.company)
    }
}

let c = new Coder('lisi', 38, 'alibaba')
c.sex = '0' // 调用set 方法
console.log(c.sex) // 调用get 方法
// 这边值得思考的问题是:
// 1. 可以发现定义get/set这种方式,如果只是从简单的获取值,设置值跟定义在构造属性其实并没有多大的区别
// 2. 好处是什么:使用get/set方式,可以对应的处理一些业务逻辑,构造里面却做不到。
3. 静态方法【static】
class People {
    constructor(name, age) {
        this.name = name
        this.age = age
        this._sex = -1 
    }

    get sex() {
        return this._sex
    }

    set sex(val){
        this._sex = val 
    }
  	// static定义的方法可以被子类继承,不可被实例调用
    static getCount() {
        return 5
    }

    showName() {
        console.log(this.name);
    }
}
console.log(People.getCount())
4. 静态属性的问题
// es6中static不可以用来定义属性,只能用来定义方法
// 如果想实现静态属性,可以使用es5的方式
// 在类下面直接定义
People.count = 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值