父级:
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(); })()
弊端:写法比较繁琐
以上就是原型继承的几种方式介绍的详细内容,更多请关注php中文网其它相关文章!
已抢47913个
抢已抢3315个
抢已抢1228个
抢已抢1359个
抢已抢1576个
抢已抢2127个
抢