JavaScript 面向对象

本文介绍了一种使用JavaScript实现面向对象编程的方法。通过自执行匿名函数创建构造函数,并利用原型链实现继承,展示了如何定义父类People和子类Student,以及如何在子类中重写父类的方法。

JavaScript 面向对象

标签: Web前端


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>面向对象Js</title>

	<script type="text/javascript">
		// 父类
		(function(){
			var n=123; //此属性 仅供 People类访问,外部无法访问
			function People(name){//构造方法,此处定义 People类
				this._name=name;
			}
			People.prototype.say = function(){ //为 People类 新增一个say方法
				alert("People-Hello "+this._name+" - "+n);
			}
			window.People=People; // People类 默认外部是不可调用的,此处暴露给window对象,使外部可以直接调用。
		}());
		// 子类
		(function(){
			function Student(name){ //定义类 Student
				this._name=name;
			}
			Student.prototype=new People();//继承父类 People
			var superSay=Student.prototype.say; //获取父类的 say方法
			Student.prototype.say=function(){ //子类重写父类的 say方法
				superSay.call(this);//子类中调用父类的方法
				alert("Student-Hello "+ this._name);
			}
			window.Student=Student; //将 Student 类暴露给 外部
		}());
		var student=new Student("ruoli"); // new 一个 Student 类的 对象
		student.say(); //调用 student 对象的 say 方法
	</script>
</head>
<body>
</body>
</html>

转载于:https://my.oschina.net/ruoli/blog/1576960

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值