继承

本文深入探讨了JavaScript中继承的概念,通过实例演示了如何使用原型链和构造函数实现继承,展示了父类People和子类Student之间的继承关系,以及如何在子类中调用父类的方法。
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>继承</title>
</head>
<body>
	<script type="text/javascript">
		/*继承:
		     被继承者: people    父类(基类、超类)
		     继承者:   student   子类(派生类)

		     继承是单向的*/

		     function People(name,age){
		     	this.name=name;
		     	this.age=age;
		     }

		     People.prototype.say=function(){
		     	console.log(this.name+' 在说话');
		     };
		     People.prototype.showInfo=function(){
		     	console.log('姓名:'+this.name+',年龄:'+this.age);
		     };

		     function Student(name,age,no,grade){
		     	People.call(this,name,age);
		     	this.no=no;
		     	this.grade=grade;
		     }

		     //方法的继承
		     for(var i in People.prototype){
		     	Student.prototype[i]=People.prototype[i];
		     }

		     Student.prototype.test=function(){
		     	console.log(this.name+' 在进行期末考试......');
		     };

		     var p=new People('李四',22);
		     p.say();
		     p.showInfo();
		     // p.test();

		     console.log('-------------------------------');

		     var s=new Student('小花',20,'1000','一年级');
		     s.say();
		     s.showInfo();
		     s.test();
	</script>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值