JS 继承与聚合

1、js的继承 https://www.liaoxuefeng.com/wiki/1022910821149312/1023021997355072

下面两张图片为百度传课讲解继承 (原型链继承 寄生继承 大体了解就好 不如廖雪峰的方法容易理解)

 

    function A (name) {
      this.name = name
    }
    A.prototype.getInfo = function() {
      console.log(this.name + '--' + this.age)
    }

    function B(name,age) {
      A.call(this,name)
      this.age = age
    }


    inherits(B,A)

    function inherits(Child,Parent) {
      function F() {}
      F.prototype = Parent.prototype
      Child.prototype = new F()
      Child.prototype.constructor = Child
    }

    // 或者这样 原理一样的
    // B.prototype = inheritFrom(A.prototype)
    // B.prototype.constructor = B



    // function inheritFrom(o) {
    //   function F() {}
    //   F.prototype = o

    //   return new F()
    // }
    var s = new B('lili',20)
    s.getInfo()
    console.log(s.__proto__ === B.prototype)
    console.log(s.__proto__.__proto__ === A.prototype)
    console.log(s instanceof A)
    console.log(s instanceof B)

 

posted @ 2019-07-15 17:22  suanmei  阅读(224)  评论(0编辑  收藏  举报