一、es6的面向对象
1、class关键字,类和构造器分开了
2、class里面直接加方法
以前的构造函数
<script>
function User(name,pass) {
this.name=name;
this.pass=pass;
}
User.prototype.showName=function () {
alert(this.name)
};
User.prototype.showPass=function () {
alert(this.pass)
};
var user1=new User('happy','2333');
user1.showName();
user1.showPass();
</script>
es6:
class User{
constructor(name,pass){
this.name=name;
this.pass=pass;
}
showName(){
alert(this.name)
}
showPass(){
alert(this.pass)
}
}
类名的开头也是大写字母,里面有constructor方法,
和自己添加的方法
二、继承
es5的继承:
function User(name,pass) {
this.name=name;
this.pass=pass;
}
User.prototype.showName=function () {
alert(this.name)
};
User.prototype.showPass=function () {
alert(this.pass)
};
function Vip(name,pass,level) {
User.call(this,name,pass);//不是很懂这一步
this.level=level;
}
Vip.prototype=new User();
Vip.prototype.constructor=Vip;//这一步也是
Vip.prototype.shoLevel=function () {
alert(this.level);
};
var vip=new Vip('HHH','22929',12);
vip.showName();
vip.showPass();
vip.shoLevel();
es6的继承:
class User{
constructor(name,pass){
this.name=name;
this.pass=pass;
}
showName(){
alert(this.name)
}
showPass(){
alert(this.pass)
}
}
class Vip extends User{
constructor(name,pass, level){
super(name,pass);//要继承父类的东西
this.level=level;
}
showName(){
alert(this.name)
}
showPass(){
alert(this.pass)
}
showLevel(){
alert(this.level)
}
}
var vip=new Vip('HHH','22929',12);
vip.showName();
vip.showPass();
vip.showLevel();