JavaScript实现继承的几种方式

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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值