js继承

作者: 小王啊_ | 来源:发表于2017-07-13 14:42 被阅读0次

    原型继承

    function superType() {
      this.issuper = true;
    }
    
    superType.prototype.superFn = function () {
      console.log('super function');
    }
    
    function subType() {
      this.issub = true
    }
    
    subType.prototype = new superType();
    
    subType.prototype.subFn = function () {
      console.log('sub funciton');
    }
    

    借用构造函数

    function superType() {
      this.issuper = true;
    }
    
    superType.prototype.superFn = function () {
      console.log('super function');
    }
    
    function subType() {
      superType.call(this);
      this.issub = true
    }
    
    subType.prototype.subFn = function () {
      console.log('sub funciton');
    }
    

    组合继承

    function superType() {
      this.issuper = true;
    }
    
    superType.prototype.superFn = function () {
      console.log('super function');
    }
    
    function subType() {
      superType.call(this);
      this.issub = true
    }
    
    subType.prototype = new superType();
    
    subType.prototype.subFn = function () {
      console.log('sub funciton');
    }
    

    原型式继承

    function object(o) {
      function F() {}
      F.prototype = o;
      return new F();
    }
    

    ECMAScript5 中已经规范这种继承方式:

    Object.create();
    

    寄生式继承

    
    function createAnotherObj(original) {
      var clone = object(original);
      clone.sayHi = function () {
        console.log('hi');
      }
      return clone;
    }
    

    相关文章

      网友评论

          本文标题:js继承

          本文链接:https://www.haomeiwen.com/subject/lamwhxtx.html