代码改变世界

javascript继承---原型继承的例子

2011-07-27 16:08  Rollen Holt  阅读(520)  评论(0编辑  收藏  举报
<html>
	<head></head>
	<body>
		<script type="text/javascript">
			function Person(name){
				this.name=name;
			}
			
			Person.prototype.getName= function(){
				return this.name;
			}
			
			function User( name , passward){
				this.passward= passward;
				this.name=name;
			}
			
			
			/**
			 * 原型继承
			 * 每次调用new User()创建的对象就会自动拥有Person对象的所有方法
			 * */
			User.prototype= new Person();
			
			User.prototype.getPassward= function(){
				return this.passward;
			}
			
			var per= new Person("Amy");
			document.writeln(per.name);
			document.writeln(per.getName());
			
			var use=new User("hello",18);
			document.writeln(use.name);
			document.writeln(use.passward);
			document.writeln(use.getName());
			document.writeln(use.getPassward());
			
			

		</script>
	</body>
</html>