原型继承的几种方式

原型继承

父级:

	function Parent(name){
		this.name=name;
	}
	Parent.prototype.sayHello=function(){
		console.log("Hello,"+this.name);
	}
  1. 原型链继承

     function Kid(){};
     Kid.prototype=new Parent("who");
    
     var k=new Kid();
     console.log(k.name); //who
     console.log(k.sayHello()); //Hello,who
    

    弊端:创建实例时无法向父级传参

  2. 构造继承

     function Kid(name){
     	Parent.call(this,name);
     };
    
     var k=new Kid("who");
     console.log(k.name); //who
     console.log(k.sayHello()); //error
    

    弊端:无法获取父级原型链属性

  3. 实例继承

     function Kid(name){
     	var p=new Parent(name);
     	return p;
     };
    
     var k=new Kid("who");
     console.log(k.name); //who
     console.log(k.sayHello()); //Hello,who
    

    弊端:实例是父级的实例

  4. 拷贝继承

     function Kid(name){
     	var p=new Parent(name);
     	for(var item in p){
     		Kid.prototype[item]=p[item];
     	}
     }
    
     var k=new Kid("who");
     console.log(k.name); //who
     console.log(k.sayHello()); //Hello,who
    

    弊端:太占用内存

  5. 组合继承

     function Kid(name){
     	Parent.call(this,name);
     }
     Kid.prototype=new Parent();
    
     var k=new Kid("who");
     console.log(k.name); //who
     console.log(k.sayHello()); //Hello,who
    

    弊端:调用了两次父类构造函数

  6. 寄生组合继承

     function Kid(name){
     	Parent.call(this,name);
     }
     (function(){
     	var p=function(){};
     	p.prototype=Parent.prototype;
     	Kid.prototype=new p();
     })()
    

    弊端:写法比较繁琐

posted @ 2017-10-15 23:19  日含  阅读(282)  评论(0编辑  收藏  举报