注释很详细,直接上代码
涉及知识点:
- 构造函数实现类
 - ES6类的写法
 - 原型链的应用
 
题干:
 
我的答案
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <script type="text/javascript">
      /**
       * 好眼熟,之前咱好像在题目规定使用class时用构造函数也写了一遍
       * 所以这里咱再来一遍,当复习了
       */
      function Human(name) {
        this.name = name;
        this.kingdom = "animal";
        this.color = ["yellow", "white", "brown", "black"];
      }
      function Chinese(name, age) {
        Human.call(this, name);
        this.age = age;
        this.color = "yellow";
      }
      //在Human的原型上定义getName方法
      Human.prototype.getName = function () {
        return this.name;
      };
      //继承Human原型(记得new而不是直接赋值,因为js赋值的是地址,会将两者绑定)
      Chinese.prototype = Object.create(Human.prototype);
      //重写Chinese的构造函数将原型链的constructor指回Chinese,正所谓作业可以抄但名字记得改
      Chinese.prototype.constructor = Chinese;
      //在Chinese的原型上定义getAge方法
      Chinese.prototype.getAge = function () {
        return this.age;
      };
      //这里我们再来用Es6的class语法来实现一遍,体验一下Es6的语法的便捷
      class Human1 {
        constructor(name) {
          this.name = name;
          this.kingdom = "animal";
          this.color = ["yellow", "white", "brown", "black"];
        }
      }
      class Chinese1 extends Human1 {
        constructor(name, age) {
          super(name);
          this.age = age;
          this.color = "yellow";
        }
        getAge() {
          return this.age;
        }
      }
    </script>
  </body>
</html>
 
博客更新不是很及时,需要看后面内容的可以看看我的
gitee仓库
牛客JS题Gitee仓库



















