es5/es6面向对象

版权声明:本文为博主原创文章,喜欢的话,可以通知我后进行转载哦! https://blog.csdn.net/maidu_xbd/article/details/87638954

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;
    }

    //添加方法--方法独立在类之外
    Person.prototype.showName = function () {
      alert(this.name);
    };
    Person.prototype.showAge = function () {
      alert(this.age);
    };

    //--------------------------------------------
    //没有专门的继承方法
    function Worker(name, age, job) {
      Person.call(this, name, age); //从父类继承要靠骗

      this.job = job;
    }

    Worker.prototype = new Person(); //没有专门继承父类方法的方式
    Worker.prototype.constructor = Worker;

    Worker.prototype.showJob = function () {
      alert(this.job);
    };

    let w = new Worker('buding', 21, '编程');

    w.showName();
    w.showAge();
    w.showJob();
  </script>
</head>

<body>

</body>

</html>

es6面向对象:(统一写法)

提供了4个关键字

    class         类声明

    constructor   构造函数

    extends       继承

    super         父类/超类

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script>
    //有单独的类声明、构造函数声明
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }

      showName() {
        alert(this.name);
      }

      showAge() {
        alert(this.age);
      }
    }

    class Worker extends Person {  //继承
      constructor(name, age, job) {
        super(name, age);

        this.job = job;
      }

      showJob() {
        alert(this.job);
      }
    }

    let w = new Worker('buding', 21, '编程');

    w.showName();
    w.showAge();
    w.showJob();
  </script>
</head>

<body>

</body>

</html>

猜你喜欢

转载自blog.csdn.net/maidu_xbd/article/details/87638954
今日推荐