0
点赞
收藏
分享

微信扫一扫

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>

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继承_子类_02




举报

相关推荐

0 条评论