JavaScript实现继承的几种方式
原型继承
特点:方便
function Parent(){
}
Parent.prototype.show=function(){
console.log("hello");
}
function Child(){
}
Child.prototype.abc=function(){
console.log("world");
}
Child.prototype=Parent.prototype;
var p=new Parent();
p.show();//hello
p.abc();//world
var c=new Child();
c.show();//hello
c.abc();//hello
原型链继承
特点:
1、更加简单、方便、易于操作
2、可以继承原型身上的方法和属性和继承函数中的方法和属性
3、不方便传承
function Parent(){
this.name="hello";
}
Parent.prototype.show=function(){
console.log("stay");
}
function Child(){
this.name="world";
}
Child.prototype=new Parent();
Child.prototype.show=function(){
console.log("here");
}
var p=new Parent();
p.show();
console.log(p.name);
var c=new Child();
c.show();
console.log(c.name);
混合继承
特点:
1、方便传参
2、可以多继承构造函数
3、 既可以继承构造函数,也可以继承原型
function Parent(s){
this.skill=s;
}
Parent.prototype.show=function(){
console.log(this.skill);
}
function Child(s){
Parent.call(this,s);
}
for(var i in Parent.prototype){
Child.prototype[i]=Parent.prototype[i];
}
Child.prototype.show=function(){
console.log("hello");
}
var p=new Parent("html");
p.show();
var c=new Child("css");
c.show();