JavaScript的几种继承方式

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"/>
</head>
<body>
	<script type="text/javascript">
	/*组合继承(最常用的继承方式)
	 使用原型链实现对原型属性和方法的继承,而通过借用构造函数的方式实现对实例属性的继承。即保证了实例都有自己的属性,又确保了方法的复用*/
	 console.log("----------组合式继承------------");
	 function Person(name){
	 	this.name=name;
	 	this.tecnologys=["java","javascript"];
	 }
	 Person.prototype.sayName=function(){
	 	console.log(this.name);
	 }
	 function Student(name,age){
	 	//继承属性
	 	Person.call(this,name);
	 	this.age=age;
	 }

	 //继承方法
	 Student.prototype=new Person();
	 Student.prototype.constructor=Student;
	 Student.prototype.sayAge=function(){
	 	console.log(this.age);
	 }


	 //test
	 var inst1=new Student("xx",18);
	 inst1.tecnologys.push("Html5");
	 inst1.sayName();
	 inst1.sayAge();
	 console.log(inst1.tecnologys);
	
	 var inst2=new Student("YY",19);	 
	 inst2.sayName();
	 inst2.sayAge();
	 console.log(inst2.tecnologys);

	 console.log("------------原型式继承--------------");
	 //原型式继承
	 function object(o){//o为被继承的对象
	 	function F(){};
	 	F.prototype=o;
	 	return new F();
	 }
	 var per={
	 	name:"MM",
	 	friends:["XH","XM"]
	 };
	 var instper1=object(per);
	 instper1.name="mm";
	 instper1.friends.push("xh");

	 var instper2=object(per);
	 instper2.name="nn";
	 instper2.friends.push("xm");
	 console.log("instper2:"+instper2.friends);//XH,XM,xh,xm
	 console.log("-----------寄生式继承--------------");
	 //寄生式继承
	 function createAnother(obj){
	 	var clone=object(obj);
	 	clone.sayHi=function(){
	 		console.log("Hi");
	 	}
	 	return clone;
	 }

	 var another1=createAnother(per);
	 console.log(another1.sayHi());
	 console.log("----------寄生组合式继承------------");
	 //寄生组合式继承(最有效的继承方式):主要是为了解决组合式继承调用两次超类型构造函数的问题
	 function inheritPrototype(subType,superType){
	 	var proto=object(superType.prototype);
	 	proto.constructor=subType;
	 	subType.prototype=proto;
	 }
	 function SuperType(name){
	 	this.name=name,
	 	this.colors=["red","green"]
	 }
	 SuperType.prototype.sayName=function(){
	 	console.log(this.name);
	 }
	 function SubType(name,age){
	 	SuperType.call(this,name);
	 	this.age=age;
	 }
	 inheritPrototype(SubType,SuperType);
	 SubType.prototype.sayAge=function(){
	 	console.log(this.age);
	 }
	 var instSub=new SubType("gg",22);
	 instSub.sayName();//gg
	 instSub.sayAge();//22
	</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值