es6新特性(二)

面向对象

在es6之前,没有类的概念,只能通过原型添加东西去模拟出类的意思。先不说麻烦,很写来也很分散。

如:

function Usr(id,name){  
   this.id=id;
   this.name=name;
}

Usr.prototype.ShowId=function(){
  alert(this.id)
}

Usr.prototype.ShowName=function(){  
  alert(this.name)
}

var usr=new Usr(1,jack);
usr.ShowId();
usr.ShowName();

es6新加了类和概念,增加class关键字,增加构造器,也不用再在外面添加方法,使用类的申明更加一体化,所有操作都可以在类里完成。

类的申明和使用

class Usr
    {
        constructor(id,name)
        {
            this.id=id;
            this.name=name;
        }

        ShowId()
        {         
            alert(this.id);
        }

        ShowName()
        {
            alert(this.name)
        }
       
    }
    var usr=new Usr(1,"jack");
    usr.ShowId();
    usr.ShowName();

继承extends

继承时需要用super调用父类的构造器

class VipUser extends User{

  constructor(id,name,level){}
    super(id,name); 
 
    this.level=level
}

ShowLevel(){
   alert(this.level)
}

当不想给父类写参数时,可以使用可变参数。如果自身还拥有自己的属性时,需注意传参时的顺序

class VipUser extends User{

  constructor(lv,...args){}
    super(...args); 
 
    this.lv=lv
}

Showlv(){
   alert(this.lv)
}

let usr=new VipUser (100,"001","jack");
    usr.ShowId();
    usr.ShowName();
    usr.ShowLv();

总结:相前ES5之前是要方便了一些,但每一次继承都需要传很多参数,还需要手动调用父类的构造器

但是比较其他高级语言,体验还是差的太远太远。

猜你喜欢

转载自blog.csdn.net/hiose89/article/details/88972258