JS继承

时间:2020-06-14 10:29:21   收藏:0   阅读:57

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);
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!