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继承的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段9——JS中的面向对象编程

js代码片段: utils/lcoalStorage/cookie

JS代码片段:一个日期离现在多久了

js常用代码片段(更新中)

js常用代码片段

Chrome-Devtools代码片段中的多个JS库