ES5 继承,js 原型与原型链的学习

<script>
    // ES5 继承方案
    function A(a,b) {
      this.a = a
      this.b = b
    }
    A.prototype.fun = function() {
      console.log(this.a,this.b)
    }
    
    // 采用混合继承的方式
    function B(a,b) {
      A.call(this,a,b)
    }
    B.prototype = new A()

    var p1 = new A(2,3)
    var p2 = new B(1,2)
    p1.fun()  // 2,3
    p2.fun()  // 1,2
    
    // ES6
    class First {
      constructor(name,age) {
        this.name = name
        this.age = age
      }
      fun1() {
        console.log(this.name,this.age)
      }
    }

    class Second extends First {
      constructor(name,age,height) {
        super(name,age)
        this.height = height
      }
      fun2() {
        console.log(this.height)
      }
    }

    class Third extends Second {
      constructor(name,age,height,play) {
        super(name,age,height)
        this.play = play
      }
      fun3() {
        console.log(`${this.name}正在玩${this.play}`)
      }
    }

    let p = new Third("tom",10,"110cm","皮球")
    p.fun1()
    p.fun2()
    p.fun3()
    // tom 10
    // 110cm
    // tom正在玩皮球
    console.log(p)

    /*
      原型链继承逻辑:
        Third  继承  Second,Second  继承  First,First  继承  Object
      
        属性或方法查找方式:
        逐步向外层查找,一旦找到,就调用该属性或方法并停止访问外层
        
        实例p   从Third的构造器查找   →    Third的原型上查找  →
                Second的构造器上查找  →   Second的原型上查找  →
                First的构造器上查找   →    First的原型上查找  →
                Object的构造器上查找  →   Object的原型上查找
    */
  </script>

上一篇:ES5中的类


下一篇:iOS+应用开发学习指南:挖自己的第一桶金