一狼电、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();