es6+最佳入门实践(12)

12.class基础用法和继承

12.1.class基础语法

在es5中,面向对象我们通常写成这样


function Person(name,age) {
    this.name = name;
    this.age = age;
}
Person.prototype.showName = function () {
    console.log(this.name);
};

let p = new Person("xiaoqiang", 10);
p.showName();

上面这种写法与传统的面向对象写法有很大的不同,让学习过其他面向对象语言的同学感到很别扭,因此,在ES6中,增加了语法糖,使用class关键字来定义类,这里说的语法糖的意思简单的理解就是另一种更便捷的写法,编译后的功能实际上是一样的

下面是ES6中定义类的语法:

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    showName(){
        console.log(this.name)
    }
}
let p = new Person("xiaoqiang2", 10);
p.showName();

注意1: constructor是默认添加的方法,当new 关键字去调用类的时候,constructor会默认被执行,即使不写这个constructor方法,也会默认添加一个空方法

constructor(name, age){
    console.log("开始执行了")
    this.name = name;
    this.age = age;
}

注意2: 在类中写的方法之间不能加逗号,否则会报错

class Person{
    constructor(name, age){
        console.log("开始执行了")
        this.name = name;
        this.age = age;
    }
    showName(){
        console.log(this.name)
    },
    showAge(){
        console.log(this.age);
    }
}
let p = new Person("xiaoqiang2", 10);
p.showName();

12.2.继承

在ES6中使用extends关键字来实现继承


class Parent{
    constructor(name, age){
        console.log("开始执行了");
        this.name = name;
        this.age = age;
    }
    showName(){
        console.log(this.name)
    }
}

//Child去继承 Parent
class Child extends  Parent{
    
}

let c = new Child('nodeing', 20);
console.log(c);

上面代码就是继承的基本写法,只是我们并没有在子类中去增加方法,此时,子类相当于去拷贝了父类

注意1: 在子类中如果重写父类的constructor方法,需要首先调用supper方法


class Parent{
    constructor(name, age){
        console.log("开始执行了");
        this.name = name;
        this.age = age;
    }
    showName(){
        console.log(this.name)
    }
}

class Child extends  Parent{
    constructor(name, age, gender){
        super(name, age);
        this.gender = gender
    }
}

let c = new Child('nodeing', 20);
console.log(c);

注意2: 如果这样写会报错:

class Child extends Parent{
    constructor(name, age, gender){
        this.gender = gender
        super(name, age);
    }
}

视频教程地址:http://edu.nodeing.com/course/50

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大地飞鸿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值