ES6中Class的使用

ES6引入Class(类)作为对象的模板,通过class关键字可以定义类,基本上ES6的class可以看作只是一个语法糖,它的绝大部分功能ES5都能做到,新的class写法只是让对象原型的写法更清晰、更像面像对象编程的语法而已。

<script>
        //ES5
        const person=function (name,age) {
            this.name=name;
            this.age=age;
            return this;
        }
        person.prototype={
            constructor:person,
            print:function () {
                console.log(this.name+" "+this.age);
            }
        }
        const p=new person('Lucy',22).print();//Lucy 22
        //ES6
        class person2{
            constructor(name,age){
                this.name=name;
                this.age=age;
                return this;
            }
            print(){
                console.log(this.name+" "+this.age);
            }
        }
        const pp=new person2('Lucy2',11).print();//Lucy2 11
    </script>

person这个类的构造方法,还定义了print方法,注意定义“类”的方法不需要加关键字function,方法与方法之间也不需要逗号隔开。

构造函数中的prototype属性,在ES6的类上面继续存在,而且类的所有方法都定义在类的prototype属性上。

定义在类中的方法都是不可以枚举的。

constructor方法是类的默认方法,通过new命令生成对象实例,自动调用该方法,一个类必须有个constructor,如果没有显示,一个空的constructor方法会被默认添加。

Class的继承

extends关键字在类的声明或类的表达式中用于创建一个类作为另一个类的子类

<script>
        class Person{
            constructor(name){
                this.name=name;
            }
            print(){
                console.log(this.name);
            }
        }
        class WW extends Person{
            print(){
                super.print();//如果子类中存在构造函数,在需要使用this之前先调用super()
                console.log('my name is '+this.name)
            }
        }
        const p=new Person('one').print();//one
        const  ww=new WW('Lucy').print();//Lucy    my name is Lucy
    </script>


猜你喜欢

转载自blog.csdn.net/Doulvme/article/details/79951589