ES6前后面向对象写法对比

2025-04-28 21:15:35

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里面直接加方法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢