13、ES6 之class

来源:互联网 发布:农村淘宝发展现状分析 编辑:程序博客网 时间:2024/04/20 10:28

 1、 定义构造函数的语法 class + 自定义的名字 {}

    function fn(){


     }
    //  上面的 等于  下面
    class Cat{
        // 构造函数本身
        constructor(){
            
        }

    }

2. 如果是静态的方法 不用new 可以直接调用

    class Cat{
        // 构造函数本身
        constructor(name){
            this.name = name;
        }
        getname(){
            return this.name
        }
        // 如果是静态的方法 不用new 可以直接调用
        static getcolor(color){
            console.log(color);
        }
    }
    Cat.getcolor(`#fff`);// 如果是静态的方法 不用new 可以直接调用

运行结果:


3、extends 继承

    class Cat{
        // 构造函数本身
        constructor(name){
            this.name = name;
        }
        getname(){
            return this.name
        }
        // 如果是静态的方法 不用new 可以直接调用
        static getcolor(color){
            console.log(color);
        }
    }
    class Dog extends Cat{
        constructor(name){
            super(name);// super 继承父类本身的constructor里面的方法
        }
        static getcolor(color){
            super.getcolor(color);
        }
    }
    let d = new Dog(`狗`);
    console.log(d.getname());

运行结果:


4、调用父类的方法 super.方法名//如果父类的是静态的在子类也只能在静态处调用,否则会报错

    class Cat{
        // 构造函数本身
        constructor(name){
            this.name = name;
        }
        getname(){
            return this.name
        }
        // 如果是静态的方法 不用new 可以直接调用
        static getcolor(color){
            console.log(color);
        }
    }
    class Dog extends Cat{
        constructor(name){
            super(name);// super 继承父类本身的constructor里面的方法
        }
        static getcolor(color){
            super.getcolor(color);//调用父类的方法
        }
    }


    Dog.getcolor(`#ccc`);

用法详细说明:

http://es6.ruanyifeng.com/#docs/class


0 0
原创粉丝点击