es6 学问总结--4

ES6 classes(类)

我们在编程过程当中经常用到面向对象,对象建立实例这个要领,然则es6中给我封装了一个class类
下边给人人引见一下!

Ecmascript5要领

//万事万物皆对象
        //1.类是由对象(笼统)泛化出来的
        //2.对象是由类建立出来的
        //3.对象叫类的详细实例
        function Person(name,age){
            this.name=name,
            this.age=age
        }
        Person.prototype.run=function(){
            console.log(this.name+" 我会跑")
        }

        var weiwei=new Person("weiwei",21);
        console.log(weiwei)
        
        function SuperMan(name,age,sex,body){
            //Person.apply(this,arguments);//继续了父类的属性
            Person.call(this,name,age,sex)//apply 传进来的是数组鸠合,call传进来的是数组

            //本身的属性
            this.body=body;
        }


        SuperMan.prototype=Object.create(Person.prototype);//继续了父类的要领

        //本身的要领    多态
        SuperMan.prototype.fly=function(){
            console.log("我会飞");
        }
        var chaoren=new SuperMan("大刚",24,"男","大")

es6要领

ES6 中有 class 语法。值得注意是,这里的 class 不是新的对象继续模子,它只是原型链的语法糖表现形式。

//1.es6供应了类来建立面向对象编程
        class Student{
            constructor(name,age){
                this.name=name;
                this.age=age;
                }
                run(){
                    console.log(this.name+" 跑啊跑")
                }
        }
       
        class SuperMan extends Student{
            constructor(name,age,xh){
                super(name,age);  //同上call
                this.xh=xh;
            }
            eat(obejectName){
                    console.log(this.name+" 喜欢吃"+obejectName)
                }
            get  xm(){
                return this.name
            }
            set  xm(value){
                //console.log(value)      //设置xm属性
                this.name=value;
            }
            static shangxue(){
                console.log("快快上学去");   //类的要领(只能类用),静态要领,对象实例不能用
            }
        }   
        let student1 = new Student('咪咪',18);
        let student2 = new SuperMan("小明",21,007)
        student2.eat("苹果");  
         //set  get  要领  
        console.log(student2.xm)    //get  挪用要领不必括号();  get猎取
        student2.xm="小红"
        console.log(student2.xm)
       // student2.shangxue()
        SuperMan.shangxue();

函数中运用 static 关键词定义组织函数的的要领和属性:
ES6 中有 class 语法。值得注意是,这里的 class 不是新的对象继续模子,它只是原型链的语法糖表现形式。

函数中运用 static 关键词定义组织函数的的要领和属性

上面代码首先用class定义了一个“类”,能够看到内里有一个constructor要领,这就是组织要领,而this关键字则代表实例对象。简朴地说,constructor内定义的要领和属性是实例对象本身的,而constructor外定义的要领和属性则是一切实例对象能够同享的。

Class之间能够经由过程extends关键字完成继续,这比ES5的经由过程修正原型链完成继续,要清楚和轻易许多。上面定义了一个Cat类,该类经由过程extends关键字,继续了Animal类的一切属性和要领。

super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor要领中挪用super要领,不然新建实例时会报错。这是由于子类没有本身的this对象,而是继续父类的this对象,然后对其举行加工。假如不挪用super要领,子类就得不到this对象。

关键字 class, extends, super

    原文作者:青石巷
    原文地址: https://segmentfault.com/a/1190000010227291
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞