javascript模擬實現繼承,繼承一次父類模板和原型對象

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'oop7.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		//實現只繼承父類的原型對象
		function extend(Sub,Sup){
			//1.用一個空函數進行中轉
			//穿件一個空函數,目的:中轉
			var F=new Function();
			F.prototype=Sup.prototype;      //實現空函數的原型對象和超類的原型對象轉換
			Sub.prototype=new F();          //原型繼承
			Sub.prototype.constructor=Sub;  //還原子類的構造器
			//保存父類的原型對象     1.方便解耦   2.能夠方便得到分類的原型對象
			Sub.superClass=Sup.prototype;        //自定義一個子類的靜態屬性,接收父類的原型對象
			if(Sup.prototype.constructor==Object.prototype.constructor){
				Sup.prototype.constructor=Sup;   //手動還原父類原型對象的構造器
			}
		}
		
		
		
		
		
		
		
		
		
		//混合繼承:原型繼承+構造函數繼承
		function Person(name,age){
			this.name=name;
			this.age=age;
			
		}
		
		Person.prototype={
			constructor:Person,
			sayName:function(){
				alert(this.name);
			}
		}
		
		function Boy(name,age,sex){
			Boy.superClass.constructor.call(this,name,age);          //綁定父類的模板函數,借用構造,支複製了父類的模板
			this.sex=sex;
		}
		
		//Boy.prototype=new Person();    //既繼承了父類的模板,又繼承了父類的原型,但因爲不習慣於在new Person時傳入參數,因此會再使用call函數繼承模板
		extend(Boy,Person);
		//給子類加上一個父類的覆蓋方法
		Boy.prototype.sayName=function(){
			alert('子類複寫方法');
		}
		var b=new Boy('張三',23,'男');
		alert(b.sex);
		b.sayName();
		Boy.superClass.sayName.call(b);     //調用父類的同名函數
		
		//3件事
		//混合繼承缺點:繼承了兩次父類的模板,一次父類的原型對象
		
		
		
		//2集成一次父類的模板,一次父類的原型對象
		//只繼承一遍父類的模板      自定義方法實現只繼承一遍父類的模板extend方法
		
		
	</script>
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>
相關文章
相關標籤/搜索