es6使用类实现继承父类构造函数的面向对象编程

1.super(要继承的参数)

//1. 继承父类的构造方法必须要用super方法
            class Father{
                constructor(x,y){
                    this.x=x;
                    this.y=y;
                }
                sum(){
                    console.log(this.x+this.y)
                }
            }
            var father=new Father(3,5)
            father.sum()
            class Son extends Father{
                constructor(x,y){
                    // 继承父类的构造方法必须要用super方法
                    super(x,y)
                }
            }
            var son=new Son(7,10)
            var son1=new Son(20,10)
            son.sum()
            son1.sum()

2.

// 2.继承父类的普通方法
            class Father{
                say(){
                    return '我是爸爸'
                }
            }
            class Son extends Father{
                // 如果儿子里面有普通函数采取就近原则,如果没有则查找父类
                // say(){
                //     console.log("我是儿子")
                // }
                say(){
                    console.log(super.say()+"的儿子")
                }
            }
            var son=new Son()
            son.say()

3.

// 子类继承父类的方法同时扩展自己的方法
            class Father{
                constructor(x,y){
                    this.x=x;
                    this.y=y
                }
                sum(){
                    console.log(this.x+this.y)
                }
            }
            class Son extends Father{
                constructor(x,y){
                    // super要放在this之前,否则会报错
                    super(x,y)
                    this.x=x;
                    this.y=y;
                    
                }
                subtract(){
                    console.log(this.x-this.y)
                }
            }
            var son=new Son(3,7)
            son.subtract()
            son.sum()

 

posted @ 2022-12-30 11:06  小闫的姑娘  阅读(41)  评论(0编辑  收藏  举报