ES6面向对象

//面向对象封装
class Student{ //定义类 (尊从首字母大写的约定)
    constructor(props){  // 构造函数 (构造函数内定于属性)
        this.name = props.name || '匿名'; // 默认'匿名'
      this.grade = props.grade || 1;
    }
    hello(){ // 在构造函数的原型上定义方法
        console.log(`你好,${this.name}同学,你在${this.grade}年级`);
    }
}



//使用
function createStudent(props) { // 对于new构造函数的封装,其优点:一是不需要new来调用,二是参数灵活
    return new Student(props || {}) // 通过new创建构造函数,并传入参数/属性
}

let niming = createStudent(); 
niming.hello();

let xiaoming = createStudent({
  name:'小明',
  grade:2
});
xiaoming.hello();



//继承
class PrimaryStudent extends Student { //class 子类 extends 父类
    constructor(props) {
        super(props); // 用super调用父类的构造方法实现属性继承
        this.age = props.age || 8; //新增子类属性
    }

    getAge() { //对子类添加方法
        console.log(`${this.name}同学,你今年${this.age}`);
    }
}


//使用继承后的
function createPrimaryStudent(props) { // 对于new构造函数的封装,其优点:一是不需要再new来调用,二是参数灵活
    return new PrimaryStudent(props || {}) // 通过new创建构造函数,并传入参数/属性
}

let xiaohong = createPrimaryStudent({
  name:'小红',
  grade:3,
  age:10
});
xiaohong.hello();
xiaohong.getAge();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值