ES6面向对象学习笔记

在ES6之前,js虽然也有面向对象的方法,但实现起来都特别繁琐,ES6借鉴了java面向对象方法的优点,成功简化了面向对象的方法,下面是我学到的ES6面向对象中继承的一个例子:

ES5写法

        // ES5实现面向对象继承
        function User(name,age){
        	this.name=name;
        	this.age=age;
        }
        User.prototype.showAge=function(){
        	alert(this.age);
        }
        User.prototype.showName=function(){
        	alert(this.name);
        }
        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(){
        	alert(this.level);
        }
        let a = new VipUser('小明',18,18);
        a.showName();
        a.showAge();
        a.showLevel();

ES6写法

        //ES6实现面向对象继承
        class User{
        	constructor(name,age){
        		this.name=name;
        		this.age=age;
        	}
        	showName(){
        		alert(this.name);
        	}
        	showAge(){
        		alert(this.age);
        	}
        }
        class VipUser extends User{
        	constructor(name,age,level){
        		super(name,age);
        		this.level=level;
        	}
        	showLevel(){
        		alert(this.level);
        	}
        }
        let a = new VipUser('刘峰',21,21);
        a.showName();
        a.showAge();
        a.showLevel();

由此对比就会明白ES6写法更接近面向对象的语言,也更能让人理解。

原文地址:https://www.cnblogs.com/lfnumber7/p/12577905.html