es5 继承

  • 原型继承缺点就是new 之后的实例对象指向同一个构造函数的原型对象,构造函数继承通过call,aplly的缺点就是无法继承构造函数原型上的属性与方法。组合继承(原型继承、构造函数继承)解决这个问题。 ```javascript

    1. // 寄生组合(原型、构造函数)继承
    2. function Parent() {
    3. this.name = 'parent'
    4. this.play = [1, 2, 3]
    5. }
    6. Parent.prototype.getName = function () {
    7. console.log(this.name)
    8. }
    9. function Child() {
    10. Parent.call(this)
    11. this.friends = 'child'
    12. }

    // 寄生继承(浅拷贝)

    1. function clone(parent, child) {
    2. child.prototype = Object.create(parent.prototype) // 或者child.prototype= new Parent()
    3. child.prototype.constructor = child
    4. }
    5. clone(Parent, Child)
    6. Child.prototype.sayName = function () {
    7. console.log(this.friends)
    8. }
    9. let person = new Child()
    10. person.sayName()
    11. person.getName()
  1. <a name="HHmPK"></a>
  2. ### es6 类继承
  3. ```javascript
  4. // es6继承
  5. class Parent {
  6. constructor() {
  7. this.name = 'parent'
  8. this.play = [1, 2, 3]
  9. }
  10. getName = function () {
  11. console.log(this.name)
  12. }
  13. }
  14. class Child extends Parent {
  15. constructor() {
  16. super()
  17. this.friends = 'child'
  18. }
  19. sayName = function () {
  20. console.log(this.friends)
  21. }
  22. }
  23. let person = new Child()
  24. person.sayName()
  25. person.getName()