// Class 的构造函数
    class Cat {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        Say() {
            return '我的名字是' + this.name + this.age + '岁了'
        }
    }
    var cat1 = new Cat('刘德华', 100);
    console.log(cat1.Say()); //我的名字是刘德华100岁了


    //通过 extends 关键字实现类的继承=============================

    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        getName() {
            return this.name;
        }
        getAge() {
            return this.age;
        }
    }
    // 默认写法全部继承👇
    class Student_ extends Person {}
    //也可以修改继承的方法 覆盖了父级的👇
    class Student extends Person {
        getName() {
            return '我覆盖了父级的方法,' + this.name;
        }
        getScore() {
            return '我是子级新增的方法,' + this.name;
        }
    }



    // 通过super关键字进行拓展父类构造器或方法=======================
    class Person2 {
        constructor(name) {
            this.name = name;
        }
        getName() {
            console.log('我是父级类getName方法输出来的');
        }
        getAge() {
            console.log(this.age);
        }
    }
    class Student2 extends Person2 {
        constructor(name, age, sex) {
            super(); //必须先调用super,才能使用constructor,才能使用this对象
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        getName() {
            super.getName(); //调用super,才能调用父类同名函数getName
            console.log('我是子级类getName方法输出来的');
        }
    }
    var stu1 = new Student2('刘德华', 100);
    stu1.getName();
    // 我是父级类getName方法输出来的
    // 我是子级类getName方法输出来的



    //     static关键字的使用===================================

    // 1、static关键字是类的方法

    // 2、只能通过类名来调用,不能被实例对象调用

    // 3、static方法也可以被继承

    class Person3 {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        static getAge() {
            console.log('我是静态属性static');
        }
    }
    class Student3 extends Person3 {}
    var person3_ = new Person3('刘德华', 100);
    var student3_ = new Student3('刘德华', 100);
    Person3.getAge(); //我是静态属性static   实例可以自己调用 但是不能被实例对象调用
    Student3.getAge(); //我是静态属性static  实例可以自己调用 但是不能被实例对象调用
    try {
        person3_.getAge(); 
    } catch (error) {
        console.log(error); //如果实例对象调用就会报错  person3_.getAge is not a function
    }
    try {
        student3_.getAge(); 
    } catch (error) {
        console.log(error);//如果实例对象调用就会报错   student3_.getAge is not a function
    }


javascript

评论
avatar
0 评论
目录