原型式继承

  1. function Person(name) {
  2. this.name = name
  3. }
  4. Person.prototype.sayHi=function(){console.log("Hi,My name is " + this.name)}
  5. function Teacher(name, subject) {
  6. Person.call(this, name)
  7. this.subject = subject
  8. }
  9. Teacher.prototype = Object.create(Person.prototype);
  10. Teacher.prototype.sayHi=function(){console.log("Hi,I'm " + this.name)}
  11. Teacher.prototype.constructor = Teacher;
  12. let p = new Person("Tony")
  13. p.sayHi()
  14. let t = new Teacher("Mike")
  15. t.sayHi()

要点

如果子构造函数prototype上有和父构造函数prototype中的同名方法,子构造函数的方法会覆盖父构造函数的

Teacher.prototype = Object.create(Person.prototype)
这句代码使得 Teacher.prototype.__proto__=== Person.prototype
同时丢失了Teacher.prototype中的constructor属性
image.png
Teacher.prototype.constructor = Teacher
这句代码可以使丢失的constructor属性再次出现
image.png

类继承

  1. class Person {
  2. constructor(name) {
  3. this.name = name
  4. }
  5. sayHi = () => {
  6. console.log("Hi,My name is " + this.name)
  7. }
  8. }
  9. class Teacher extends Person {
  10. constructor(name, subject) {
  11. super(name)
  12. this.subject = subject
  13. }
  14. sayHi = () => {
  15. console.log("Hi,I'm " + this.name)
  16. }
  17. }
  18. let p = new Person("Tony")
  19. p.sayHi()
  20. let t = new Teacher("Mike")
  21. t.sayHi()