ES5和ES6面向对象的写法

匿名 (未验证) 提交于 2019-12-03 00:21:02
面向对象:
ES5:

function User(name,age){
this.name = name;
this.age = age;
}

User.prototype.showName=function(){
console.log(this.name);
}
User.prototype.showAge=function(){
console.log(this.age);
}

function Vipuser(name,age,level){
User.call(this,name,age);
this.level = level;
}
Vipuser.prototype = new User();
Vipuser.prototype.constructor = Vipuser;

Vipuser.prototype.showLevel=function(){
console.log(this.level);
}

var v1 = new Vipuser('hum',12,3);
v1.showName();
v1.showAge();
v1.showLevel();

ES6: 面向对象:注意User后面没有括号
class User{
constructor(name,age){
this.name = name;
this.age = age;
}
showName(){
console.log(this.name);
}
showAge(){
console.log(this.age);
}
}

class Vipuser extends User{
constructor(name,age,level){
super(name,age);
this.level = level;
}
showLevel(){
console.log(this.level);
}
}
var v1 = new Vipuser('han',10,2);
v1.showName();
v1.showAge();
v1.showLevel();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!