JS组合继承

组合继承

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>组合继承</title>
  </head>
  <body>
    <script>
      function Person(name, age) {
        this.name = name;
        this.age = age;
      }

      Person.prototype.setName = function (name) {
        console.log(this.name);
        this.name = name;
      };

      function Student(name, age, price) {
        Person.call(this, name, age);
        this.price = price;
      }

      Student.prototype = new Person(); //为了看到父类型的方法
      Student.prototype.constructor = Student; //修正constructor属性
      Student.prototype.setPrice = function (price) {
        this.price = price;
      };

      var stu = new Student("张三", 18, 100);
      stu.setName("李四");
      stu.setPrice(200);
      console.log(stu.name, stu.age, stu.price);
      console.dir(stu);
    </script>
  </body>
</html>

 

posted @ 2023-05-18 22:41  前端那点事  阅读(33)  评论(0编辑  收藏  举报