JS继承
Posted 见嘉于世
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS继承相关的知识,希望对你有一定的参考价值。
ES5继承
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
alert(`My name is ${this.name}.`);
return this.name;
}
Person.prototype.constructor = Person;
function Student(name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sayGrade = function () {
alert(`I am a grade ${this.grade} student.`);
return this.grade;
}
let s1 = new Student("Mike", 12, 4);
let s2 = new Student("Helen", 18, 12);
ES6继承
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
sayName () {
alert(`My name is ${this.name}.`);
return this.name;
}
}
class Student extends Person {
constructor (name, age, grade) {
super(name, age);
this.grade = grade;
}
sayGrade () {
alert(`I am a grade ${this.grade} student.`);
return this.grade;
}
}
let s1 = new Student("Mike", 12, 4);
let s2 = new Student("Helen", 18, 12);
以上是关于JS继承的主要内容,如果未能解决你的问题,请参考以下文章