zoukankan      html  css  js  c++  java
  • [javascript]寄生组合式继承

    子类需要继承超类的原型

    function object(o){
                    function f(){};
                    f.prototype = o;
                    return new f();
            }
    
                
    function inheritPrototype( subType ,superType ,proto){
                    var prototype = object( superType );
                    prototype.constructor = subType;
                    subType.prototype = prototype;
                    
                    for( p in proto ){
                        subType.prototype[p] = proto[p];
                }
            }

     创建互相继承的子类

    function Root(){
                this.name = "Root";
    }
    
    var RootPrototype = {
                reWrite : function(){return "root_rewrite";},
                sayName : function(){console.log(this.name);}
    };
    
    for(p in RootPrototype){
                Root.prototype[p] = RootPrototype[p];
    }
    
    
    function Note_1(){
                this.name = "Note_1";
    }
    
    var Note_1Prototype = {
                reWrite : function(){return "note_1_rewrite";},
                note_1_own : function(){console.log("note_1_own");}
    };
    
    function Note_1_1(){
                this.name = "Note_1_1";
    }
    
    var Note_1_1Prototype = {
                reWrite : function(){return "note_1_1_rewrite";},
                note_1_1_own : function(){console.log("note_1_1_own");}
    };

     继承

    inheritPrototype( Note_1 ,Root.prototype ,Note_1Prototype);
    inheritPrototype( Note_1_1 ,Note_1.prototype ,Note_1_1Prototype);

     测试

    var _root = new Root();
    var note_1 = new Note_1();
    var note_1_1 = new Note_1_1();
    
    console.log(_root);
    console.log(note_1);
    console.log(note_1_1);
    
    _root.sayName();
    note_1.sayName();
    note_1_1.sayName();
    
    note_1.note_1_own();
    note_1_1.note_1_1_own();
    
    
    console.log(note_1_1 instanceof Root);
    console.log(note_1_1 instanceof String);
    console.log(note_1 instanceof Root);
  • 相关阅读:
    递归 迷宫问题
    中缀表达式转后缀表达式
    栈实现后缀表达式计算

    单向环形链表
    站在巨人的肩上
    C#自宿主API,不依赖IIS
    MySQL 安装失败解决办法
    第一话
    村上春树《眠》读书笔记
  • 原文地址:https://www.cnblogs.com/yiyide266/p/6934067.html
Copyright © 2011-2022 走看看