Node 继承

面向对象是一种非常重要的编程思想,三大特性就是继承、多态、封装。JavaScript本身就是面向对象的编程语言,在ES6引入class关键字后,让我们可以更便捷的使用面向对象思想。

1. 封装,即将通用的动作、属性组合为类。

//父类存放通用的属性,动作
class Base {
    constructor(context) {
        this.name = 'super';
        this.requestTime = new Date();
        this.context = context;
    }
    async getById(opts) {
        //
    }
    async findAll() {
        //
    }
    async findByName () {
        //
    }
    async beginTransaction () {
        //
    }
}

2. 继承,即将通用的动作、属性放入父类,子类包含父类的通用动作、属性的同时,也有自己特殊的动作、属性。

//父类存放通用的属性,动作
class Base {
    constructor(context) {
        this.name = 'super';
        this.requestTime = new Date();
        this.context = context;
    }
    async getById(opts) {
        //
    }
    async findAll() {
        //
    }
}

//子类包含父类的通用动作、属性,同时也有自己特殊的动作、属性
//将各种独有的动作、属性,放在子类
class User extends Base {
    constructor(context) {
        super(context);
        this.phone = context.phone;
        this.login = context.login;
    }    
    async isUserLoginUsed(login) {
        //
    }
    async getById(opts) {
        let {table, id} = opts;
        let sql = "select id from :table where id = :id";
    }
}

3. 多态,即继承自父类的子类之间是有差异性的。

// 此class的方法和上面的方法名完全一致,但是动作却不一样
class User extends Base {
    constructor(context) {
        super(context);
        this.phone = context.phone;
        this.login = context.login;
    }    
    async isUserLoginUsed(login) {
        //select login from users 
    }
    async isUserPhoneUsed (phone) {
        //
    }
    //虽然和上面的User类都继承同一个父类,且方法名一样,但是动作却是完全不一样
    async getById(opts) {
        let {table1, table2, id} = opts;
        let sql = `select t1.id, t2.name from :table t1, inner join :table2 t2
            where t1.id = t2.id and t.id = :id`;
    }
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值