JavaScript-ES6继承
  TEZNKK3IfmPf 2023年11月12日 32 0
  • 在子类中通过​​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>

JavaScript-ES6继承

在 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>

JavaScript-ES6继承

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月12日 0

暂无评论

推荐阅读
TEZNKK3IfmPf