ES6中的类(Class)的写法

1.传统ES5中的class用法

//ES5的对应写法
        (function(){
            //定义类、构造函数
            function User(name,age){
                this.name=name;
                this.age=age;
            }

            //定义原型方法
            User.prototype.show=function(){
                console.log('...');
            }

            //定义静态方法
            User.run=function(){
                console.log('...');
            }

            window.User=user;
        })();

1.ES6中的class用法

    class User{
            //实例化类时默认会执行构造函数
            constructor(name,age){
                //初始化对象的语句
                this.name=name;
                this.age=age;
            }

            //原型方法
            show(){
                console.log('...');
            }

            //静态方法
            static run(){
                console.log('...');
            }
        }

3.ES5的继承写法

    //ES5的继承
        function Father(){
        }
        Father.prototype.show=function(){
        }

        function Son(){
            //继承第一句:让子类实例化的对象具备父类的所有属性
            Father.apply(this,arguments);
        }
        //继承第二句:让子类实例化对象具备父类的所有原型方法
        Son.prototype=Object.create(Father.prototype);

        //继承第三句:找回丢失的构造函数
        Son.prototype.constructor=Son;

        Son.prototype.run=function(){
        }

4.ES6的继承写法(简单到丧心病狂)

//ES6的继承
        class Son extends Father{
            constructor(){
                super();
            }
        }

5.super关键字

super可以用在类的继承中,或者对象字面量中,super指代了整个prototype或者proto指向的对象

作用:

super 关键字用于访问父对象上的函数。

用法:

super([arguments]); // 访问父对象上的构造函数
super.functionOnParent([arguments]); // 访问父对象上的方法

猜你喜欢

转载自blog.csdn.net/hahahhahahahha123456/article/details/81589915