es6的类class

定义一个类的方法为:

class Person{
                constructor(name,age){
                    this.name=name;
                    this.age=age;
                }
                showName(){
                    console.log(`我的名字为:${this.name}`)        //注意,不要加逗号
                }
                showAge(){
                    console.log(`我的年龄为:${this.age}`);
                }
            }
            let p1 = new Person("Mr.V",23);
            p1.showAge();
            p1.showName();
            console.log(p1);

注意class没有预解析,只有先定义后使用!

类的方法添加和读取都有方法监听,getter和setter方法:使用如下:

<script>
        class Person{
            constructor(){
                this.name = "微微"
            }
            set age(val){
               console.log(`存值为:${val}`);
            }
            get age(){
               return `取值啦`;
            }
           
        }
        let p1 =new Person();
        p1.age=12;                    //存值为:12
        console.log(p1.age);            //取值啦
    </script>

get和set必须同时设置,不然不能拿到值!

上面设置的方法都是实例方法,就是通过创建子集来调用的方法,还有种静态方法,通过父级调用的方法:如下

<script>
        class Person{
            constructor(name){
                this.name=name
            }
            static aaa(){
                return `我是静态方法`;
            }
            showname(){
                return `我的名字为${this.name}`;
            }
        }
        let p1 = new Person("张三");      
        console.log(p1.showname());    //我的名字为张三
        console.log(Person.aaa());    //我是静态方法
    </script>

类的继承:

<script>
        class Person {
            constructor(name) {
                this.name = name
            }
            showname() {
                console.log(`我是父类的showname方法:${this.name}`);
            }
        }
        class Student extends Person { //继承person类
            constructor(name, skill) {
                super(name); //super()方法继承父类属性
                this.skill = skill;
            }
            showname() {
                super.showname(); //super()方法继承了父类方法
                console.log(`我是子类的showname方法:${this.name}`);
            }
            showskill() {
                console.log(`我的技能是${this.skill}`);
            }
        }
        let p2 = new Student("微微", "逃学");
        p2.showname();
        p2.showskill();
        // 我是父类的showname方法:微微
        // class继承.html:28 我是子类的showname方法:微微
        // class继承.html:31 我的技能是逃学
    </script>

猜你喜欢

转载自blog.csdn.net/William526/article/details/85727744