当前位置: 首页> 健康> 养生 > 牛客JS题(十九)继承

牛客JS题(十九)继承

时间:2025/7/12 2:10:02来源:https://blog.csdn.net/m0_73756108/article/details/140886237 浏览次数:0次

注释很详细,直接上代码

涉及知识点:

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

关键字:牛客JS题(十九)继承

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: