方法一:使用class

  1. class Person{
  2. constructor(name, age){
  3. this.name = name
  4. this.age = age
  5. }
  6. sayHi(){
  7. console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
  8. }
  9. }
  10. class Student extends Person {
  11. constructor(name, age, school, grade) {
  12. super(name, age)
  13. this.school = school
  14. this.grade = grade
  15. }
  16. study(){
  17. console.log("好好学习,天天向上")
  18. }
  19. }
  20. const lilei = new Student('李雷', 12, '实验小学', 5)
  21. lilei.sayHi()
  22. lilei.study()

方法二: 使用原型链

  1. function Person(name, age){
  2. this.name = name
  3. this.age = age
  4. }
  5. Person.prototype.sayHi = function(){
  6. console.log(`hi, my name is ${this.name}, I'm ${this.age} year's old.`)
  7. }
  8. function Student(name, age, school, grade){
  9. this.school = school
  10. this.grade = grade
  11. Person.call(this, name, age)
  12. }
  13. Student.prototype.__proto__ = Person.prototype
  14. Student.prototype.study = function(){
  15. console.log("好好学习,天天向上")
  16. }
  17. const lilei = new Student('李雷', 12, '实验小学', 5)
  18. lilei.sayHi()
  19. lilei.study()

如果禁止使用Student.prototype.__proto__ = Person.prototype,则应使用下面的代码代替

  1. const f = function(){}
  2. f.prototype = Person.prototype
  3. Student.prototype = new f()