ES6 类和继承

1.创建类和生成实例

//创建class
    class Star{
      //类的共有属性放到 constructor 里面
      constructor(uname,age){
        this.uname =uname
        this.age =age
      }
      //添加方法
      sing(song){
        console.log(this.uname +"唱"+ song)
      }
    }
    // new实例创建对象
   let ldh= new Star('liudehua',45)
   let zxy= new Star('zhangxueyou',46)
   console.log(ldh)
   console.log(zxy)
    //调用方法
   ldh.sing("'恭喜发财'")
image.png
1.通过class 关键字创建类,类名首字母大写
2.类里面有个constructor函数,可以接受传递过来的参数,同时返回实例对象
3. constructor 函数 只要new 生成实例,自动调用这个函数。不写也会自动生成
4.多个函数方法之间不需要加逗号分割

2.类的继承extends和super

class Father{
      constructor(){

      }
      money(){
        console.log(100)
      }
    }

    class Son extends Father{

    }
    let son = new Son()

    son.money() //100
   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(x,y) //调用父类的构造函数
      }
    }
    let son = new Son(1,2)

    son.sum() //3
super关键字用于访问和调用对象父类的函数。可以调用父类的构造函数,也可以调用普通函数
 class Father{
      say(){
        return '我是爹'
      }
    }

    class Son extends Father{
      say(){

        console.log(super.say() +'的儿子')
      }   
    }
    let son = new Son()

    son.say() //我是爹的儿子
super 关键字访问调用父类上的函数
 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(x, y)  //放到this前面调用父类的constructor

                this.x = x;
                this.y = y;

            }
            subtract() {
                console.log(this.x - this.y)
            }
        }
        var son = new Son(5, 4);
        son.subtract()
        son.sum()

注意子类的构造函数使用super,必须放到this前面(必须先调用父类的构造方法,在使用子类的构造方法)

总结:

1.在ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象
2.类的面得共有属性和方法一定要加this 使用
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。