zoukankan      html  css  js  c++  java
  • ES5 和 ES6的继承

    ES5:

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
        <script>
        //定义构造函数
        function Person(name, age){
          this.name=name;
          this.age=age;
        }
        //在原型 prototype 上定义方法
        Person.prototype.show=function (){
          alert(this.name);
          alert(this.age);
        };
        //用到类的时候,实例化 new 一个
        let p = new Person("blue",18);
        p.show();
    
        //ES5的继承-------------------------------------------
        //定义子类的构造函数
        function Worker(name, age, job){
          Person.call(this, name, age);
          this.job=job;
        }
    
        Worker.prototype=new Person();  //继承父类的 prototype
        //继承父类的prototype后,自身的 constructor 会乱掉,需要还原一下
        Worker.prototype.constructor=Worker;  
    
        //添加 Worker 自己的方法
        Worker.prototype.showJob=function (){
          alert(this.job);
        };
    
        let w=new Worker('blue', 18, '打杂的');
    
        w.show();
        w.showJob();
        </script>
      </head>
      <body>
    
      </body>
    </html>

    ES6:

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
        <script>
        //ES6的面向对象 ,class 用来专门声明类的
        class Person{
          constructor(name, age){ // constructor 构造函数
            this.name=name;
            this.age=age;
          }
    
          show(){ // 直接在class里面写方法
            alert(this.name);
            alert(this.age);
          }
        }
    
        //ES6的继承--------------------------------------
    
        class Worker extends Person{  // 告诉系统 Worker 继承于 Person
          constructor(name, age, job){  // 子类的constructor,参数比父类只多不少
            super(name, age); //调父类的构造函数,用super关键字把需要的父类的参数传过来,需要什么就传什么
            this.job=job; //子类自己的参数
          }
    
          showJob(){  //加上自己需要的,子类的方法
            alert(this.job);
          }
        }
    
        //类的使用方法和 ES5 没什么不同,实例化
        let w=new Worker('blue', 18, '打杂的');
    
        w.show(); //调父类的方法
        w.showJob();  //调自己的方法
    
        /*
          
         */
        </script>
      </head>
      <body>
    
      </body>
    </html>
  • 相关阅读:
    【面试】前端基本
    【echart】学习笔记
    【Django】url传递参数
    【HTML】section
    【jquery】获取元素高度
    【ztree】ztree例子
    【CSS3】块级元素与行内元素的区别
    Vue 项目中应用
    Vue 指令
    Vue 组件
  • 原文地址:https://www.cnblogs.com/smile-fanyin/p/15002168.html
Copyright © 2011-2022 走看看