ES5和ES6的面向对象编程简单了解

ES5

<script>
    //prototype---------ES5
    function Animal(id,name,age) {
       this.id = id;
       this.name = name;
       this.age = age;
    }
    Animal.prototype.run = function () {
        console.log(this.id,this.name,this.age);
        console.log("Animal run")
    }
    let a1 = new Animal("001","a","23");
    a1.run();

    //建立继承关系
    function Pig(id,name,age,weight) {
        Animal.apply(this,[id,name,age]);//ES5语法继承类--此处也可用call,用来改变this指向
        this.weight = weight;
    }
    //继承
    Pig.prototype = new Animal();
    Pig.prototype.eat = function () {
        console.log(this.name+"再吃饭,它已经"+this.weight+"kg重了");
    }
    let pi1 = new Pig("001","pig","23","250");
    pi1.eat()
</script>

ES6
ES6支持了class,extends关键字,也支持Class的静态方法,一切看起来越来越像Java开发人员所熟悉的那一套机制。

//ES6------------以class的方式来规整代码,
    class Person {//父类
        constructor(id,name,age){
            this.id = id;
            this.name = name;
            this.age =age;
        }

        hello(){
            console.log(this.id,this.name,this.age)
            console.log("say hello")
        }
    }
    //父类实例
    let p1 = new Person("001","jhon","23");
    p1.hello()
	
	//子类,建立继承
    class Student extends Person{

        constructor(id,name,age,dept,num){
            super(id,name,age);//子类的构造函数可以通过super关键字来调用父类的构造函数。

            this.dept = dept;
            this.num = num;
        }
        writeRead(){
            console.log(this.name+"在读马克思")
        }
        listen(){
            console.log(this.name+"在听"+this.dept+"的课程")
        }
    }
    let s1 = new Student("Computer","B1406");
    s1.writeRead()
    let s2 = new Student("002","Tom","44","物联网","B1234");
    s2.listen()

猜你喜欢

转载自blog.csdn.net/qq_43219422/article/details/89351712