牛客JS题(十九)继承

注释很详细,直接上代码

涉及知识点:

  1. 构造函数实现类
  2. ES6类的写法
  3. 原型链的应用

题干:
在这里插入图片描述

我的答案

<!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仓库

  • 33
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码对我眨眼睛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值