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);
发布了83 篇原创文章 · 获赞 18 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Abudula__/article/details/84911162