javascript通过原型实现继承

上一篇文章中我们说明了原型是什么,这里通过原型来实现继承。

先直接上一段代码,并通过注释来解释。

function Plane(color){   //建立一个父类对象
    		this.color=color;
    	}
    	Plane.prototype.fly=function(){   //通过原型来给父类赋予方法
    		console.log('flying');
    	}
    	
    	function Fighter(color){   //建立子类
    		Plane.call(color);    //通过call函数来实现父类属性的初始化
    		this.bullit=[];
    	}
    	inheritPrototype(Fighter,Plane);   //通过这个函数来实现子类继承父类
    	Fighter.prototype.shoot=function(){   //通过原型来给子类赋予方法
    		console.log('biu biu biu ');
    	}
    	
    	function inheritPrototype(child,parent){
    		//第一步,新建一个对象
    		//将这个对象的原型 赋值给传进的参数   原型->parent
    		//返回一个对象
    		var proto=Object.create(parent.prototype);
    		//第二三步实现子类和父类通过原型来链接。
    		proto.constructor=child;
    		child.prototype=proto;
    	}
    	
    	var fighter=new Fighter('red');
    	fighter.fly();
    	console.log(fighter);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值