JavaScript-ES6继承
ES6 之前的继承
- 在子类中通过
call/apply
方法然后在借助父类的构造函数 - 将子类的原型对象设置为父类的实例对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6继承</title>
<script>
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.say = function () {
console.log(this.name, this.age);
}
function Student(name, age, score) {
// 1.在子类中通过call/apply方法借助父类的构造函数
Person.call(this, name, age);
this.score = score;
this.study = function () {
console.log("day day up");
}
}
// 2.将子类的原型对象设置为父类的实例对象
Student.prototype = new Person();
Student.prototype.constructor = Student;
let stu = new Student("BNTang", 18, 99);
stu.say();
</script>
</head>
<body>
</body>
</html>
在 ES6 中如何继承,在子类后面添加 extends
并指定父类的名称,在子类的 constructor
构造函数中通过 super
方法借助父类的构造函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6继承</title>
<script>
// ES6开始的继承
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
console.log(this.name, this.age);
}
}
// 以下代码的含义: 告诉浏览器将来Student这个类需要继承于Person这个类
class Student extends Person {
constructor(name, age, score) {
super(name, age);
this.score = score;
}
study() {
console.log("day day up");
}
}
let stu = new Student("zs", 18, 98);
stu.say();
</script>
</head>
<body>
</body>
</html>
分类:
ECMAScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具