多语言展示
当前在线:743今日阅读:167今日分享:16

ES6前后面向对象写法对比

ES6前后面向对象写法对比
方法/步骤
1

//1.旧写法//旧写法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 u1=new User('哮天犬大战嫦娥',12346789); u1.showName(); u1.showPass();//继承function User(name,pass){ this.name=name; this.pass=pass; } User.prototype.showName=function(){ alert(this.name); } User.prototype.showPass=function(){ alert(this.pass); } //在原来的基础上多写个vip 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); } var u1=new VipUser('哮天犬大战嫦娥',12346789,'9999级'); u1.showName(); u1.showPass(); u1.showLevel();

2

//2、es6的写法//面向对象class User{ constructor(name,pass){ this.name=name; this.pass=pass; } showName(){ alert(this.name); } showPass(){ alert(this.pass); } } var u1=new User('哮天犬大战嫦娥',12346789); u1.showName(); u1.showPass(); //继承class User{ constructor(name,pass){ this.name=name; this.pass=pass; } showName(){ alert(this.name); } showPass(){ alert(this.pass); } } class VipUser extends User{ constructor(name,pass,level){ super(name,pass); this.level=level; } showLevel(){ alert(this.level); } } var u1=new VipUser('哮天犬大战嫦娥',12346789,'9999级'); u1.showName(); u1.showPass(); u1.showLevel();

3

结论:1.//原来的面向对象的写法 //既是类又是构造函数----在其它语言里不会这样 //参数与方法分开了2.//ES6新推出写法 //1.class关键字、构造器与类分开了 //2.class里面直接加方法

推荐信息