类与继承

类与继承

简单对比一下 es6以前与现在类与继承的一些简单变化

类:

  es5:

function Person(name,age){
            this.name=name;
            this.age=age;    
        }
        Person.prototype.say=function(){
            console.log(`我的名字是:${this.name},我今年${this.age}了.`);
        }
        let Person1=new Person('xqzi','25');
        Person1.say();//我的名字是:xqzi,我今年25了.

es6:

class Dog{
            constructor(name,age) {
                this.name=name;
                this.age=age;
            }
            yelp(){
                console.log(`我的名字是:${this.name},我今年${this.age}了.`);
            } 
        }
        let dog1=new Dog('xqzi','5');
        dog1.yelp();//我的名字是:xqzi,我今年5了.

继承  继承以上父类

es5:

function BigPerson(name,age,bigLevel){
            Person.call(this,name,age);
            this.bigLevel=bigLevel;
        }
        BigPerson.prototype=new Person();
        BigPerson.prototype.constructor=BigPerson;
        BigPerson.prototype.sayLevel=function(){
            console.log(`我的等级是:${this.bigLevel}`);
        }
        let BigPerson1=new BigPerson('qzy','16','4');
        BigPerson1.say();//我的名字是:qzy,我今年16了.
        BigPerson1.sayLevel();//我的等级是:4

es6:

class BigDog extends Dog{
            constructor(name,age,level){
                super(name,age);
                this.level=level;
            }
            sayLevel(){
                console.log(`我的等级是:${this.level}`);
            }
        }
        let BigDog1=new BigDog('xqzi','6','大狗');
        BigDog1.yelp();//我的名字是:xqzi,我今年6了.
        BigDog1.sayLevel();//我的等级是:大狗

个人感觉规范了很多,也很方便,向老大哥靠齐了呀。

 

posted @ 2019-03-04 21:52  善良的小邱子  阅读(516)  评论(0)    收藏  举报