javascript设计模式-继承
阅读原文时间:2023年07月11日阅读:1

javascript继承分为两种:类式继承(原型链、extend函数)、原型式继承(对继承而来的成员的读和写的不对等性、clone函数)。

  1. 类式继承-->prototype继承:

     function Person(name){  
         this.name = name;  
     }  
     Person.prototype.getName = function(){  
         return this.name;  
     }
    
     //继承  
     function Author(name,books){  
         Person.call(this,name);  
         this.books = books;  
     }  
     Author.prototype = new Person();  
     Author.prototype.constructor = Author;  
     Author.prototype.getBooks = function(){  
         return this.books;  
     }
    
     var author = new Author("zap","javascript程序设计");  
     console.log(author);
  2. 类式继承-->extend函数:

     function extend(subClass,superClass){  
         var F = function(){};  
         F.prototype = superClass.prototype;  
         subClass.prototype = new F();  
         subClass.prototype.constructor = subClass;
     subClass.superClass = superClass.prototype;  
     if(superClass.prototype.constructor == Object.prototype.constructor){  
         superClass.prototype.constructor =  superClass;  
     }  
    } /\*Class Person\*/ function Person(name){ this.name = name; } Person.prototype.getName = function(){ return this.name; } function Author(name,books){ Author.superClass.constructor.call(this,name);

    // Person.call(this,name);
    this.books = books;
    }
    extend(Author,Person);
    Author.prototype.getBooks = function(){
    return this.books;
    }

     var author = new Author("zap","javascript程序设计");  
     console.log(author);  
     console.log(author.getName());  
     console.log(author.getBooks());
  3. 原型式继承-->clone函数:(原型式继承更能节约内存)

     var Person  ={  
         name:"zap",  
         age:"26",  
         toString:function(){  
             console.log(this.name + "@" + this.age);  
         }  
     }
    
     var author = clone(Person);  
     author.name = "zap";  
     author.toString();
    
     function clone(object){  
         function F(){}  
         F.prototype = object;  
         return new F;  
     }

    附上以类式继承实现的就地编辑demo,原型式方式实现和类式继承方式相差无几,不在此列举。


    类式继承解决方案