【前端Js】原型继承的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hj7jay/article/details/78246497
原型继承
父级:
 function Parent(name){
        this.name=name;
    }
    Parent.prototype.sayHello=function(){
        console.log("Hello,"+this.name);
    }
  
原型链继承
function Kid(){};
Kid.prototype=new Parent("who");

var k=new Kid();
console.log(k.name); //who
console.log(k.sayHello()); //Hello,who
弊端:创建实例时无法向父级传参

构造继承
function Kid(name){
    Parent.call(this,name);
};

var k=new Kid("who");
console.log(k.name); //who
console.log(k.sayHello()); //error
弊端:无法获取父级原型链属性


实例继承
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
弊端:实例是父级的实例


拷贝继承
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
弊端:太占用内存

组合继承
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
弊端:调用了两次父类构造函数

寄生组合继承
function Kid(name){
    Parent.call(this,name);
}
(function(){
    var p=function(){};
    p.prototype=Parent.prototype;
    Kid.prototype=new p();
})()
弊端:写法比较繁琐

没有更多推荐了,返回首页