ES6 class 类 继承

  • 概念:讲对象中公共的属性或方法封装成一个模版(ES5中构造函数)
  • 作用:创建对象
  • 语法:
//使用class关键字,Person就是一大类名,可以理解为构造函数的名称
class Person {

}
// 使用new关键字创建实例
const xx = new Person()
  • 类里面添加属性:
//使用class关键字,Person就是一大类名,可以理解为构造函数的名称
class Star {
    // 类的公共属性放在 constructor 内
    constructor(name) {
        this.name = name
    }
}
// 使用new关键字创建实例
const ldh = new Star('ldh')
  • 类里面添加方法:
//使用class关键字,Person就是一大类名,可以理解为构造函数的名称
class Star {
    // 类的公共属性放在 constructor 内
    constructor(name) {
        this.name = name
    }
    sing(){
        console.log('唱歌');
    }
}
// 使用new关键字创建实例
const ldh = new Star('刘德华')
ldh.sing()
  • 继承extends
class Father {
    constructor(name) {
        this.name = name
    }
    sing() {
        console.log('唱歌');
    }
}
// Son继承Father的属性和方法
class Son extends Father { }
const son = new Son('大头儿子')
son.sing()
  • super的使用
  1. 使用场景一 :   子类中想要调用父类的方法
    class Father {
        constructor(name) {
            this.name = name
        }
        sing() {
            console.log('唱歌');
        }
    }
    class Son extends Father {
        hobby(){
            // 子类使用父类的方法
            super.sing()
        }
    }
    const son = new Son('大头儿子')
    son.hobby()
  2. 使用场景二 : 子类中有自己的属性,需要调用 super 传入父类构造函数的参数,同时保证 super  在 this 前面调用 
    class Father {
        constructor(name) {
            this.name = name
        }
        sing() {
            console.log('唱歌');
        }
    }
    class Son extends Father {
        // 子类的 constructor 内要把父类的 构造函数参数写在前面,再写自己的参数
        constructor(name, age) {
            // 如果子类有自己的属性,则先调用 super ,把父类构造函数内的参数传入,并且 super 的调用需要写在 this 的前面
            super(name)
            this.age = age
        }
        hobby() {
            // 子类使用父类的方法
            super.sing()
        }
    }
    const son = new Son('大头儿子', 18)
    console.log(son);//{name: '大头儿子', age: 18}
    son.hobby()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值