ES6面向对象
ES6之前的面向对象如何写的,想必大家都知道大部分都是凑出来的。先看看之前的代码面向对象该怎么写?
<script type="text/javascript">
function User(name,pass){
this.name=name;
this.pass=pass;
}
User.prototype.showName=function(){
alert(`姓名:${this.name}\n密码:${this.pass}`);
}
let li=new User('zhangsan','4599332');
li.showName();
</script>
ES6面向对象
1.增加了class关键字,构造器和类分开了
2.class里面直接加方法—————————
<script type="text/javascript">
class User{
constructor(name,pass){
this.name=name;
this.pass=pass;
}
showName(){
alert(`姓名:${this.name}\n密码:${this.pass}`);
}
}
let li=new User('zhangsan','4599332');
li.showName();
</script>
ES6之前的继承
function User(name,pass){
this.name=name;
this.pass=pass;
}
User.prototype.showName=function(){
alert(`姓名:${this.name}\n密码:${this.pass}`);
}
function VipUser(name,pass,level){
User.call(this,name,pass);
this.level=level;
}
VipUser.prototype=new User();
VipUser.prototype.constructor=VipUser;
VipUser.prototype.showLevel=function (){
alert(this.level);
}
let v1=new VipUser('lisi','33445566','3');
v1.showName();
v1.showLevel();
ES6的继承
class User{
constructor(name,pass){
this.name=name;
this.pass=pass;
}
showName(){
alert(`姓名:${this.name}\n密码:${this.pass}`);
}
}
class VipUser extends User{
constructor(name,pass,level){
super(name,pass);
this.level=level;
}
showLevel(){
alert(this.level);
}
}
let v1=new VipUser('lisi','4599332','99');
v1.showName();
v1.showLevel();